python – pandas数据帧中的Groupby

请考虑以下数据集:

a        b
0        23
0        21
1        25
1        20
1        19
2        44
2        11

如何在b列中找到大于20的值的百分比,并且根据列a位于同一个簇中.
我的代码给了我每组的相同价值.

NN20 = [x for x in b if (x > 20)]
percent_20 = lambda x: float(len(NN20)) / float(len(b))
pnn20=data.groupby('a').apply(percent_20) 

最佳答案 IIUC:

In [179]: df.groupby('a')['b'].apply(lambda x: x.gt(20).mean())
Out[179]:
a
0    1.000000
1    0.333333
2    0.500000
Name: b, dtype: float64

要么

In [183]: df.groupby('a')['b'].transform(lambda x: x.gt(20).mean())
Out[183]:
0    1.000000
1    1.000000
2    0.333333
3    0.333333
4    0.333333
5    0.500000
6    0.500000
Name: b, dtype: float64
点赞