python-3.x - 按降序对两列最频繁的组合进行排序

标签 python-3.x sorting pandas numpy

我有这样的数据框

+---+---+---
|  A|  B| C|
+---+---+---
|  1|  3| 1|
|  2|  1| 1|
|  2|  3| 1|
|  1|  2| 1|
|  3|  1| 1|
|  1|  2| 1|
|  2|  1| 1|
|  1|  3| 1|
|  1|  2| 1|
+---+---+---

我想将数据缩减为仅按降序排列的两列(A 和 B)的最频繁组合 输出应该看起来像

+---+---+-----+
|  A|  B|count|
+---+---+-----+
|  1|  2|    3|
|  2|  1|    2|
+---+---+-----+

我写了这段代码,但它没有排序

import pandas as pd
import numpy as np
data=pd.read_csv("file.csv",sep=',')
gps = data[['A','B','C']]
gps1=gps.groupby(['A','C'])


gps1=gps1.count()
gps1.columns=['count']
gps1.sort_values(['count'],ascending=False)
print(gps1)

最佳答案

使用nlargest

gps.groupby(['A', 'B']).size().nlargest(2)

A  B
1  2    3
   3    2
dtype: int64

gps.groupby(['A', 'B']).size().nlargest(2).reset_index(name='count')

enter image description here

关于python-3.x - 按降序对两列最频繁的组合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621802/

相关文章:

python - 将带有小计的 pandas groupby 结果转换为相对值

python - ImageChops.difference 不适用于简单的 png 图像

python - 这个 Python 字符串中的 {0} 是什么意思?

java - 尝试获取正确的月份以显示最高和最低值

python - PIP 安装 Numpy 抛出错误 "ascii codec can' t decode byte 0xe2"

python - 对一组动态选择的列应用 Groupby 和聚合

python - 调用了错误的 python 解释器

python - 将包含字符串的列表和嵌套的字符串列表拆分为平面列表

excel - 使用VBA对Excel表格进行排序时如何引用列中的当前周单元格?

sorting - (快速)对 POSIX sh 中的文件列表进行排序