想象一下以下 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 列,它有两个不同的值 property1 和 property2。对于 ID “bar”,两列只有一个不同的值。
如果按 id 分组,我正在寻找的代码会为我提供那些计数大于 1 的列的名称。所以结果应该是列 A 的名称,因为它包含非不同的值。
df.groupby(['id'])
我只知道如何获取计数(出现次数)大于 1 的 ID。但这不是我最终要寻找的。p>
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/