Python 熊猫在两个数据帧上计数范围

Python 熊猫在两个数据帧上计数范围,python,pandas,Python,Pandas,假设我有两个数据帧: (1) 范围列表 (2) 实际值 import pandas as pd import numpy as np from datetime import datetime, timedelta SLA = {'Wertebereich': [5, 10, 15, 20, 25]} SLA = pd.DataFrame(data=SLA) messwerte = pd.DataFrame(np.random.randint(0,30,size=10),

假设我有两个数据帧: (1) 范围列表 (2) 实际值

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

SLA = {'Wertebereich': [5, 10, 15, 20, 25]}
SLA = pd.DataFrame(data=SLA)


messwerte = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Messwerte"],
                  index=pd.date_range("20180101", periods=10))


       Wertebereich 
0             5      
1            10      
2            15     
3            20      
4            25      

            Messwerte
2018-01-01         22
2018-01-02         13
2018-01-03         14
2018-01-04         17
2018-01-05          1
2018-01-06         11
2018-01-07         17
2018-01-08          6
2018-01-09          4
2018-01-10         10
现在,我想在SLA中添加一个新列(“计数”),将每个范围内的所有事件相加

我创建了一个迭代解决方案,但想知道是否有比我的解决方案更快处理10000x3000行的方法

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

SLA = {'Wertebereich': [5, 10, 15, 20, 25]}
SLA = pd.DataFrame(data=SLA)


messwerte = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Messwerte"],
                  index=pd.date_range("20180101", periods=10))


#print(SLA.to_string())
#print(messwerte.to_string())


###############
SLA["Count"] = 0

for i in range(0, len(SLA)-1):
    counter = 0
    treshold_min = SLA.iloc[i].get('Wertebereich')
    treshold_max = SLA.iloc[i+1].get('Wertebereich')
    for x in range(0, len(messwerte)):
        val = messwerte.iloc[x].get('Messwerte')
        print('---- ' + str(val) )
        if ((val >= treshold_min) & (val < treshold_max)):
            counter = counter +1

    SLA.ix[i,'Count'] = counter

print(SLA.to_string())
print(messwerte.to_string())
将熊猫作为pd导入
将numpy作为np导入
从datetime导入datetime,timedelta
SLA={'Wertebereich':[5,10,15,20,25]}
SLA=pd.DataFrame(数据=SLA)
messwerte=pd.DataFrame(np.random.randint(0,30,大小=10),
列=[“Messwerte”],
索引=pd.日期范围(“20180101”,期间=10))
#打印(SLA.to_字符串())
#打印(messwerte.to_string())
###############
SLA[“计数”]=0
对于范围(0,长度(SLA)-1)内的i:
计数器=0
treshold_min=SLA.iloc[i].get('Wertebereich')
treshold_max=SLA.iloc[i+1].get('Wertebereich')
对于范围(0,len(messwerte))内的x:
val=messwerte.iloc[x].get('messwerte')
打印('---'+str(val))
如果((val>=treshold_最小值)和(val
任何想法都值得赞赏

谢谢

试试这个:

messwerte['Messwerte'].value_counts(bins=SLA['Wertebereich'])
输出:

(20.0, 25.0]     5
(4.999, 10.0]    2
(10.0, 15.0]     1
(15.0, 20.0]     0
Name: Messwerte, dtype: int64

查看一下
pd.cut