查找组中最频繁的观察 [英] Find most frequent observation in group
本文介绍了查找组中最频繁的观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
DataFrame:
DataFrame:
B = pd.DataFrame({'b':['II','II','II','II','II','I','I','I'],
'MOST_FREQUENT':['1', '2', '2', '1', '1','1','2','2']})
我需要在每个组的MOST_FREQUENT
列中获得最频繁的值:
I need to get the most frequent value in a column MOST_FREQUENT
for each group:
pd.DataFrame({'b':['I','II'],
'MOST_FREQUENT':['2','1']})
我找到的唯一线索-mode()
,但不适用于DataFrameGroupBy
The only clue i found - mode()
, but is not applieble to DataFrameGroupBy
我需要一个解决方案,该解决方案满足熊猫的.agg()
功能
I need a solution, which satisfies the pandas' .agg()
function
推荐答案
您可以使用apply
:
print (B.groupby('b')['MOST_FREQUENT'].apply(lambda x: x.mode())
.reset_index(level=1, drop=True).reset_index())
b MOST_FREQUENT
0 I 2
1 II 1
另一种解决方案是使用 SeriesGroupBy.value_counts
并返回第一个index
值,因为value_counts
对值进行排序:
Another solution is use SeriesGroupBy.value_counts
and return first index
value, because value_counts
sorts values:
print (B.groupby('b')['MOST_FREQUENT'].apply(lambda x: x.value_counts().index[0])
.reset_index())
b MOST_FREQUENT
0 I 2
1 II 1
您可以使用 most_common
You can use most_common
from collections import Counter
print (B.groupby(['b']).agg(lambda x: Counter(x).most_common(1)[0][0]).reset_index())
b MOST_FREQUENT
0 I 2
1 II 1
这篇关于查找组中最频繁的观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文