首页 > 解决方案 > 如何在python中选择每列的值完全相同的多个(如2或5)频繁行?

问题描述

假设我有一个数据框

       A         B          C          
0      1         2          a
1      6         5          c
2      5         4          b 
3      2         5          d 
4      4         9          q
5      1         2          a  
6      5         4          b
7      1         2          a
8      1         4          c 

我想找到最频繁的 2 行(行中的每个值都完全相同)和相应的频率。在此示例中,该行将是 1、2、a 和 5,4,b。频率为 3 和 2。

我知道如何找到我可以使用模式功能的最频繁的行。我也知道我可以使用 Counter 在一列中选择多个频繁值。如何在python中选择每列的值完全相同的多个(如2或5)频繁行?非常感谢!

标签: pythonpandascount

解决方案


集合.计数器

您可以使用collections.Counter从您的数据帧派生的元组。这个想法是将每个数据帧行转换为 a tuple,以便它是可散列的,然后再馈送到Counter.

from collections import Counter

c = Counter(map(tuple, df.values))
res = c.most_common(2)

print(res)

[((1, 2, 'a'), 3), ((5, 4, 'b'), 2)]

GroupBy + 大小

对于基于 Pandas 的方法,您可以使用GroupBywith size,然后排序并选择前 2 个:

res = df.groupby(df.columns.tolist()).size()\
        .sort_values(ascending=False)\
        .head(2)

print(res)

A  B  C
1  2  a    3
5  4  b    2
dtype: int64

根据其他答案,pd.Series.nlargest是排序然后提取前n 个元素的有效替代方法。


推荐阅读