本文介绍了 pandas 分组比:高于阈值的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个想要在其上使用groupby
的DataFrame,但我正在寻找一些不寻常的函数来进行汇总.我想使每个组中观察值的百分比高于某个阈值.例如,如果阈值为0,则DataFrame
I have a DataFrame that I'm looking to use a groupby
on but I'm looking for a little bit of an unusual function to aggregate with. I would like to get the percentage of observations in each group above a certain threshold. For example, with a threshold of 0, the DataFrame
df = pd.DataFrame(dict(day=[1, 1, 1, 2, 2, 2, 3, 3, 3, 4], value=[0, 4, 0, 4, 0, 4, 0, 4, 0, 4]))
df
day value
0 1 0
1 1 4
2 1 0
3 2 4
4 2 0
5 2 4
6 3 0
7 3 4
8 3 0
9 4 4
应该成为
df_group = pd.DataFrame(dict(day=[1, 2, 3, 4], value=[.33, .67, .33, 1.0]))
df_group
day value
0 1 0.33
1 2 0.67
2 3 0.33
3 4 1.00
我还在处理相当大的数据集,因此,我希望将计算时间考虑在内.
I am also working with a fairly large data set, so I'd appreciate taking computation time into account.
推荐答案
>>> df.groupby('day')['value'].apply(lambda c: (c>0).sum()/len(c))
day
1 0.333333
2 0.666667
3 0.333333
4 1.000000
Name: value, dtype: float64
这篇关于 pandas 分组比:高于阈值的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!