python - 获取非重复值计数大于指定值的列

标签 python pandas group-by pandas-groupby

想象一下以下 Python Pandas 数据框:

df = pd.DataFrame({'id' : ['foo', 'bar', 'foo'], \
                   'A' : ['property1', 'property1', 'property2'], \
                   'B' : ['test', 'test', 'test'] })
from tabulate import tabulate
print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+------+------+
|    | A         | B    | id   |
|----+-----------+------+------|
|  0 | property1 | test | foo  |
|  1 | property1 | test | bar  |
|  2 | property2 | test | foo  |
+----+-----------+------+------+

在这里您可以看到,对于 ID “foo”,列 B 只有一个唯一(不同)值,即 test。但对于 A 列,它有两个不同的值 property1property2。对于 ID “bar”,两列只有一个不同的值。

如果按 id 分组,我正在寻找的代码会为我提供那些计数大于 1 的列的名称。所以结果应该是列 A 的名称,因为它包含非不同的值。

df.groupby(['id'])

我只知道如何获取计数(出现次数)大于 1 的 ID。但这不是我最终要寻找的。

df['id'].value_counts().reset_index(name="count").query("count > 1")["id"]

感谢任何提示。

最佳答案

使用:

#filter column of interest
a = (df.groupby(['id'])['A','B'].nunique() > 1).any()

print (a)
A     True
B    False
dtype: bool

#if need test all columns without id
a = (df.set_index('id').groupby('id').nunique() > 1).any()
print (a)
A     True
B    False
dtype: bool

最后一个过滤器:

b = a.index[a]
print (b)
Index(['A'], dtype='object')

关于python - 获取非重复值计数大于指定值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47037250/

相关文章:

python - 使用引用组标准化 Pandas GroupBy 数据框中的数据

Pandas 合并具有相同值和相同索引的行

php - MySQL 查询中的组逗号分隔元素

python - 如何将多个 Pandas 系列合并到一个数据框,其中系列具有值列表

python - 列值替换

Python-代码不保留定义中分配的变量

python-3.x - 带有外部列的 Pandas 数据透视表

R计算Dataframe中每列的值

mysql - group by中带数据函数的query如何优化

Python Sockets - 如何关闭服务器?