本文介绍了打印目标列的前 2 个经常出现的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下所示的三列,并试图返回第三列的 top1 和 top2 最高计数.我希望生成此输出,如 预期输出 所示.数据:
I have three columns like shown below, and trying to return top1 and top2 highest count of the third column. I want this output to be generated as shown in the expected output .DATA :
打印(df)
AGE GENDER rating
0 10 M PG
1 10 M R
2 10 M R
3 4 F PG13
4 4 F PG13
代码:
s = (df.groupby(['AGE', 'GENDER'])['rating']
.apply(lambda x: x.value_counts().head(2))
.rename_axis(('a','b', 'c'))
.reset_index(level=2)['c'])
输出:
print (s)
a b
4 F PG13
10 M R
M PG
Name: c, dtype: object
预期输出:
print (s[F])
('PG13')
print(s[M])
('PG13', 'R')
推荐答案
我认为您需要:
s = (df.groupby(['AGE', 'GENDER'])['rating']
.apply(lambda x: x.value_counts().head(2))
.rename_axis(('a','b', 'c'))
.reset_index()
.groupby('b')['c']
.apply(list)
.to_dict()
)
print (s)
{'M': ['R', 'PG'], 'F': ['PG13']}
这篇关于打印目标列的前 2 个经常出现的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!