想象以下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'])
我只知道如何获得其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')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句