如何获取表中出现频率最高的行

Myk*_*tko 15 python numpy mode frequency pandas

如何获取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
Run Code Online (Sandbox Code Playgroud)

预期结果:

   col_1  col_2 col_3
0      1      1     A
Run Code Online (Sandbox Code Playgroud)

编辑:我需要最频繁的行(作为一个单位)而不是可以使用该mode()方法计算的最频繁的列值。

WeN*_*Ben 11

查看 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  
Run Code Online (Sandbox Code Playgroud)


Div*_*kar 9

随着 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
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找性能,请将字符串列转换为数字,然后使用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)
Run Code Online (Sandbox Code Playgroud)


Myk*_*tko 2

在 Pandas 1.1.0 中。可以使用该方法value_counts()来计算 DataFrame 中的唯一行数:

df.value_counts()
Run Code Online (Sandbox Code Playgroud)

输出:

col_1  col_2  col_3
1      1      A        2
       0      C        1
              B        1
              A        1
0      1      A        1
Run Code Online (Sandbox Code Playgroud)

此方法可用于查找最频繁的行:

df.value_counts().head(1).index.to_frame(index=False)
Run Code Online (Sandbox Code Playgroud)

输出:

   col_1  col_2 col_3
0      1      1     A
Run Code Online (Sandbox Code Playgroud)