如何获取表格中最常见的行

15

如何在DataFrame中获取最频繁的行?例如,如果我有以下表格:

   col_1  col_2 col_3
0      1      1     A
1      1      0     A
2      0      1     A
3      1      1     A
4      1      0     B
5      1      0     C

预期结果:

   col_1  col_2 col_3
0      1      1     A

编辑:我需要最常见的一行(作为一个单元)而不是可以使用 mode() 方法计算出的最常见列值。

5个回答

12

检查groupby

df.groupby(df.columns.tolist()).size().sort_values().tail(1).reset_index().drop(0,1)
   col_1  col_2 col_3  
0      1      1     A  

1
另一种方法是 df.groupby(df.columns.tolist(), as_index=False).size().sort_values('size').tail(1).drop('size', 1) - Mykola Zotko

10

使用 NumPy 的 np.unique 函数 -

In [92]: u,idx,c = np.unique(df.values.astype(str), axis=0, return_index=True, return_counts=True)

In [99]: df.iloc[[idx[c.argmax()]]]
Out[99]: 
   col_1  col_2 col_3
0      1      1     A

如果你想要提高性能,将字符串列转换为数字,然后使用np.unique -

a = np.c_[df.col_1, df.col_2, pd.factorize(df.col_3)[0]]
u,idx,c = np.unique(a, axis=0, return_index=True, return_counts=True)

4
你可以使用 groupby 和 size 来实现此操作:
df = df.groupby(df.columns.tolist(),as_index=False).size()
result = df.iloc[[df["size"].idxmax()]].drop(["size"], axis=1)
result.reset_index(drop=True) #this is just to reset the index

你需要检查你的代码。你如何获取 'size' 列? - Mykola Zotko
你说得对,我添加了“as_index=False”,这是我在写下来时不知怎么漏掉的。谢谢! - DDD1

3

npi_indexed 库可以帮助我们在处理“groupby”类型的问题时更加高效地执行某些操作,而且性能与 numpy 相当。因此,这是一种可替代的、与 @Divakar 的基于 np.unique() 的解决方案非常相似的方法:

arr = df.values.astype(str)
idx = npi.multiplicity(arr)
output = df.iloc[[idx[c.argmax()]]]

2
在Pandas 1.1.0中,可以使用方法value_counts()来计算DataFrame中唯一行的数量:
df.value_counts()

输出:

col_1  col_2  col_3
1      1      A        2
       0      C        1
              B        1
              A        1
0      1      A        1

这种方法可用于查找最常见的行:

df.value_counts().head(1).index.to_frame(index=False)

输出:

   col_1  col_2 col_3
0      1      1     A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接