简体   繁体   English

如何在python pandas中获得每列n个最频繁或最高的值?

[英]How to get the n most frequent or top values per column in python pandas?

my dataframe looks like:我的数据框看起来像:

df:
    A   B
0   a   g
1   f   g
2   a   g
3   a   d
4   h   d
5   f   a

for top 2 most frequent values per column (n=2), the output should be:对于每列前 2 个最频繁的值 (n=2),输出应为:

top_df:
    A   B
0   a   g
1   f   d

Thank you谢谢

This should work这应该工作

n = 2
df.apply(lambda x: pd.Series(x.value_counts().index[:n]))

Something like this could help喜欢的东西, 可以帮助

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]

SOLUTION:解决方案:
To get the n most frequent values, just subset .value_counts() and grab the index:要获得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)

INPUT DATA:输入数据:

# test.csv
A,B
a,g
f,g
a,g
a,d
h,d
f,a

OUTPUT:输出:

   A  B
0  a  g
1  f  d

NOTE: I have taken solution from @myccha , another answer from this post, as I found his answer more helpful, added it as METHOD 2.注意:我从@myccha那里得到了解决方案,这是这篇文章的另一个答案,因为我发现他的答案更有帮助,将其添加为方法 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM