如果我有这样的表:
df = pd.DataFrame({
'hID': [101, 102, 103, 101, 102, 104, 105, 101],
'dID': [10, 11, 12, 10, 11, 10, 12, 10],
'uID': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'],
'mID': ['A', 'B', 'A', 'B', 'A', 'A', 'A', 'C']
})
我可以在 Qlik 中执行 count(distinct hID)
来为唯一 hID 计算 5 个计数。如何使用 pandas 数据框在 python 中做到这一点?或者也许是一个numpy数组?同样,如果要执行 count(hID)
我将在 Qlik 中得到 8。在 pandas 中等效的方法是什么?
最佳答案
计算不同的值,使用 nunique
:
df['hID'].nunique()
5
只计算非空值,使用count
:
df['hID'].count()
8
计算包括空值在内的总值,使用size
属性:
df['hID'].size
8
编辑以添加条件
使用 bool 索引:
df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])
OR 使用 查询
:
df.query('mID == "A"')['hID'].agg(['nunique','count','size'])
输出:
nunique 5
count 5
size 5
Name: hID, dtype: int64
关于python - 像 Qlik 一样计算 pandas 数据框中的列中的唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45759966/