繁体   English   中英

如何计算Pandas Dataframe中变量的唯一组合

[英]How to count unique combinations of variable in a Pandas Dataframe

我正在使用pandas来计算数据帧中变量集的唯一组合。 我目前正在使用.groupby()函数,但我认为我缺少它的一部分功能。

示例代码:

import pandas
df = pd.DataFrame([['A','C','G'],
                   ['A','C','H'],
                   ['A','D','G'],
                   ['A','D','H'],
                   ['B','E','I'],
                   ['B','F','I']], columns=['a','b','c'])
df

   a  b  c
0  A  C  G
1  A  C  H
2  A  D  G
3  A  D  H
4  B  E  I
5  B  F  I

我想知道,对于每个独特的价值a,它有多少不同的b? 在此示例中,所需输出为A:2,B:2,因为A具有两个唯一的b值,B具有两个唯一的b值。

如果我计算每个的唯一c,我会期望A:2,B:1。

我目前的代码是:

df.groupby(['a','b'],as_index=False).count().groupby(['a'], as_index=False).count()[['a','b']]

   a  b
0  A  2
1  B  2

df.groupby(['a','c'], as_index=False).count().groupby(['a'],as_index=False).count()[['a','c']]

   a  c
0  A  2
1  B  1

这给了我正确的结果,但我认为应该有办法避免两组groupby()和count(),不是吗?

nunique怎么nunique

df.groupby('a')['b'].nunique()
Out[36]: 
a
A    2
B    2
Name: b, dtype: int64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM