简体   繁体   English

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

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

I'm using pandas to count unique combinations of sets of variables in a dataframe. 我正在使用pandas来计算数据帧中变量集的唯一组合。 I'm currently using the .groupby() function, but I think I'm missing part of it's functionality. 我目前正在使用.groupby()函数,但我认为我缺少它的一部分功能。

Example code: 示例代码:

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

Say I want to know, for every unique value a, how many different b's does it have? 我想知道,对于每个独特的价值a,它有多少不同的b? In this example, the desired output is A: 2, B:2 because A has two unique b values and B has two unique b values. 在此示例中,所需输出为A:2,B:2,因为A具有两个唯一的b值,B具有两个唯一的b值。

If I were counting the unique c's per a, I would expect A: 2, B: 1. 如果我计算每个的唯一c,我会期望A:2,B:1。

My current code is: 我目前的代码是:

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

This gives me the correct result, but I think there should be a way to avoid two sets of groupby() and count(), no? 这给了我正确的结果,但我认为应该有办法避免两组groupby()和count(),不是吗?

How about nunique ? 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