聚合Pandas列基于列范围中的值

时间:2017-04-16 02:35:20

标签: python-3.x pandas numpy dataframe

数据集:

enter image description here

在使用数据帧pandas时需要输出如下所示。我想根据PRCP范围由PRCP分组并汇总计数。请指教

enter image description here

1 个答案:

答案 0 :(得分:0)

import pandas as pd

df = pd.DataFrame({'CLDATE':['1/1/16','1/10/16','1/11/16','11/12/16','11/13/16','11/14/16','11/15/16','11/16/16'],
                   'count':[64396,49877,41603,41124,45839,45846,52719,59626],'PRCP':[0,1.8,0,0,0,0,0,0.24]})


df['precipate_Range']=pd.cut(df['PRCP'],[0,1,2,3],right=False,labels=['0-1','1-2','2-3'])

df.groupby('precipate_Range')['count'].agg({'Sum':'sum'}).reset_index()

输出:

  precipate_Range       Sum
0             0-1  351153.0
1             1-2   49877.0
2             2-3       NaN