像Qlik中那样在pandas数据框中的列中计算唯一值? [英] Counting unique values in a column in pandas dataframe like in Qlik?
本文介绍了像Qlik中那样在pandas数据框中的列中计算唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个这样的表:
If I have a table like this:
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)
来得出5个唯一的hID.我该如何在Python中使用Pandas数据框?还是一个numpy的数组?同样,如果执行count(hID)
,我将在Qlik中得到8.在大熊猫中做这件事的等效方法是什么?
I can do count(distinct hID)
in Qlik to come up with count of 5 for unique hID. How do I do that in python using a pandas dataframe? Or maybe a numpy array? Similarly, if were to do count(hID)
I will get 8 in Qlik. What is the equivalent way to do it in pandas?
推荐答案
计算离散值,请使用nunique
:
df['hID'].nunique()
5
仅计算非空值,请使用count
:
Count only non-null values, use count
:
df['hID'].count()
8
计算包括空值在内的总值,请使用size
属性:
Count total values including null values, use size
attribute:
df['hID'].size
8
编辑以添加条件
使用布尔索引:
Edit to add condition
Use boolean indexing:
df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])
或使用query
:
df.query('mID == "A"')['hID'].agg(['nunique','count','size'])
输出:
nunique 5
count 5
size 5
Name: hID, dtype: int64
这篇关于像Qlik中那样在pandas数据框中的列中计算唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文