python - 如何在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)频繁行?非常感谢!
解决方案
集合.计数器
您可以使用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 的方法,您可以使用GroupBy
with 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 个元素的有效替代方法。
推荐阅读
- iar - IAR是否兼容Win10
- javascript - 获取 html 文件而不是获取 json 并创建 html 会很糟糕吗?为什么?
- macos - 在 macos 10.13.6 上安装 Bazel 0.16.1 时权限被拒绝
- apache-spark - Spark 中的迭代 RDD/Dataframe 处理
- javascript - 路由器 click.native 在 Vue 中传递了错误的参数
- r - 无法让 R 读取 GPS 坐标
- firebase - Http 请求在 Google 助理的 Firebase webhook 中不起作用
- c++ - 如何在 LLVM 通行证中获取 C++ 析构函数?
- php - 修剪用户在 content.php wordpress 文件中输入的摘录
- python - H5 十六进制数据