Python 像Qlik一样计算pandas数据框中列中的唯一值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45759966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting unique values in a column in pandas dataframe like in Qlik?
提问by Alhpa Delta
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']
})
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?
我可以count(distinct hID)
在 Qlik 中为唯一的 hID 计算 5 的计数。我如何使用 Pandas 数据框在 python 中做到这一点?或者也许是一个 numpy 数组?同样,如果这样做,count(hID)
我将在 Qlik 中获得 8。在熊猫中这样做的等效方法是什么?
回答by Scott Boston
Count distict values, use nunique
:
计算 distict 值,使用nunique
:
df['hID'].nunique()
5
Count only non-null values, use count
:
只计算非空值,使用count
:
df['hID'].count()
8
Count total values including null values, use size
attribute:
计算包括空值在内的总值,使用size
属性:
df['hID'].size
8
Edit to add condition
编辑以添加条件
Use boolean indexing:
使用布尔索引:
df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])
OR using query
:
或使用query
:
df.query('mID == "A"')['hID'].agg(['nunique','count','size'])
Output:
输出:
nunique 5
count 5
size 5
Name: hID, dtype: int64
回答by oumar
If I assume data is the name of your dataframe, you can do :
如果我假设 data 是您的数据框的名称,您可以执行以下操作:
data['race'].value_counts()
this will show you the distinct element and their number of occurence.
这将向您显示不同的元素及其出现次数。
回答by piRSquared
Or get the number of unique values for each column:
或者获取每列的唯一值的数量:
df.nunique()
dID 3
hID 5
mID 3
uID 5
dtype: int64
New in pandas 0.20.0
pd.DataFrame.agg
新进 pandas 0.20.0
pd.DataFrame.agg
df.agg(['count', 'size', 'nunique'])
dID hID mID uID
count 8 8 8 8
size 8 8 8 8
nunique 3 5 3 5
You've always been able to do an agg
within a groupby
. I used stack
at the end because I like the presentation better.
您总是能够agg
在groupby
. 我stack
在最后使用,因为我更喜欢演示文稿。
df.groupby('mID').agg(['count', 'size', 'nunique']).stack()
dID hID uID
mID
A count 5 5 5
size 5 5 5
nunique 3 5 5
B count 2 2 2
size 2 2 2
nunique 2 2 2
C count 1 1 1
size 1 1 1
nunique 1 1 1
回答by Uma Raj
To count unique values in column, say hID
of dataframe df
, use:
要计算列中的唯一值,例如hID
dataframe df
,请使用:
len(df.hID.unique())
回答by Manu Siddhartha
you can use unique property by using len function
您可以使用 len 函数使用唯一属性
len(df['hID'].unique()) 5
len(df['hID'].unique()) 5