如何获取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()方法计算的最频繁的列值。
发布于 2020-10-05 21:14:45
在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发布于 2020-09-28 22:52:22
检查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 发布于 2020-09-28 23:00:30
有了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)https://stackoverflow.com/questions/64104341
复制相似问题