pandas聚合计数高于阈值

时间:2018-06-09 08:35:07

标签: python-3.x python-2.7 pandas

我有一个我想要分组的数据框。我想使用df.agg来确定超过180的长度。

有没有办法为它编写一个小函数?

我试过了len(nice_numbers[nice_numbers > 180]),但它没有用。

df = pd.DataFrame(data = {'nice_numbers': [60, 64, 67, 70, 73, 75, 130, 180, 184, 186, 187, 187, 188, 194, 199, 195, 200, 210, 220, 222, 224, 250, 70, 40, 30, 300], 'activity': 'sleeping', 'sleeping', 'sleeping', 'walking', 'walking', 'walking', 'working', 'working', 'working', 'working', 'working', 'restaurant', 'restaurant', 'restaurant', 'restaurant', 'walking', 'walking', 'walking', 'working', 'working', 'driving', 'driving', 'driving', 'home', 'home', 'home}')
df_gb = df.groupby('activity')
df_gb.agg({'count_frequency_over_180'})

谢谢

1 个答案:

答案 0 :(得分:3)

按照gt的比较列创建布尔值掩码,使用汇总sum计算True个值:

df1 = (df['nice_numbers'].gt(180)
                         .groupby(df['activity'], sort=False)
                         .sum()
                         .astype(int)
                         .reset_index())

set_index创建的索引sum的类似解决方案:

df1 = df.set_index('activity')['nice_numbers'].gt(180).sum(level=0).astype(int).reset_index()
print (df1)
     activity  nice_numbers
0    sleeping             0
1     walking             3
2     working             5
3  restaurant             4
4     driving             2
5        home             1

编辑:

有关nice_numbers列使用agg的更多指标:

agg = ('abobe_180_count', lambda x: x.gt(180).sum()), ('average', 'mean')
df1 = df.groupby('activity')['nice_numbers'].agg(agg).reset_index()
print (df1)
     activity  abobe_180_count     average
0     driving                2  181.333333
1        home                1  123.333333
2  restaurant                4  192.000000
3    sleeping                0   63.666667
4     walking                3  137.166667
5     working                5  187.000000