[英]How to get the n most frequent or top values per column in python pandas?
我的数据框看起来像:
df:
A B
0 a g
1 f g
2 a g
3 a d
4 h d
5 f a
对于每列前 2 个最频繁的值 (n=2),输出应为:
top_df:
A B
0 a g
1 f d
谢谢
这应该工作
n = 2
df.apply(lambda x: pd.Series(x.value_counts().index[:n]))
喜欢的东西, 这可以帮助
maxes = dict()
for col in df.columns:
frequencies = df[col].value_counts()
# value counts automatically sorts, so just take the first 2
max[col] = frequencies[:2]
解决方案:
要获得n
最频繁的值,只需使用.value_counts()
子集并获取索引:
import pandas as pd
df = pd.read_csv('test.csv')
# METHOD 1 : Lil lengthy and inefficient
top_dict = {}
n_freq_items = 2
top_dict['A'] = df.A.value_counts()[:n_freq_items].index.tolist()
top_dict['B'] = df.B.value_counts()[:n_freq_items].index.tolist()
top_df = pd.DataFrame(top_dict)
print(top_df)
df.apply(lambda x: pd.Series(x.value_counts()[:n_freq_items].index))
# METHOD 2 : Small, and better : taking this method from @myccha. As I found this better
top_df = df.apply(lambda x: pd.Series(x.value_counts()[:n_freq_items].index))
print(top_df)
输入数据:
# test.csv
A,B
a,g
f,g
a,g
a,d
h,d
f,a
输出:
A B
0 a g
1 f d
注意:我从@myccha那里得到了解决方案,这是这篇文章的另一个答案,因为我发现他的答案更有帮助,将其添加为方法 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.