Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:groupby两列nunique_Python_Pandas_Statistics - Fatal编程技术网

Python 熊猫:groupby两列nunique

Python 熊猫:groupby两列nunique,python,pandas,statistics,Python,Pandas,Statistics,我有以下样本集 CustID Condition Month Reading Consumption 0 108000601 True June 20110606 28320.0 1 108007000 True July 20110705 13760.0 2 108007000 True Augu

我有以下样本集

        CustID     Condition      Month        Reading  Consumption 
0     108000601         True       June       20110606      28320.0
1     108007000         True       July       20110705      13760.0
2     108007000         True     August       20110804      16240.0
3     108008000         True  September       20110901      12560.0
4     108008000         True    October       20111004      12400.0
5     108000601        False   November       20111101       9440.0
6     108090000        False   December       20111205      12160.0
7     108008000        False    January       20120106      11360.0
8     108000601         True   February       20120206      10480.0
9     108000601         True      March       20120306       9840.0
下面的groupby为我提供了我正在寻找的部分内容

dfm.groupby(['Condition'])['CustID'].nunique()

但是我怎样才能得到符合这两个条件的唯一ID呢?e、 g

Condition
True      3
False     3
Both      2

不确定这是否是最“熊猫”的方式,但您可以使用
set
来比较每个分区中的用户(Python
set
数据结构是一个哈希表,它将自动丢弃重复项):


我建议在
CustID
上分组。然后,我们可以查看每个组,轻松确定每个唯一id是否只有
True
、只有
False
,或者两者都有。然后我们只需使用
系列。value\u counts()

Both     2
False    1
True     1
Name: Condition, dtype: int64

我对熊猫还不熟悉,所以也不确定它是否是pandonics,但这确实有效!尽管有更多的熊猫,但这并没有在完整的数据集中返回我想要的结果。我只得到了所有匹配的“CustID”或“CustID”。不过,我将继续使用此策略,使其在整个数据集上对我有效。谢谢。很有趣。。。如果你发现你的数据的一个子集重现了这个问题,请随意编辑你的问题并附加它,我来看看。
custid_true = set(dfm[dfm['Condition']==True].CustID)
custid_false = set(dfm[dfm['Condition']==False].CustID)
custid_both = custid_true.intersection(custid_false)
n_custid_both = len(custid_both)
def categorize(s):
    if s.all():
        return 'True'
    elif not s.any():
        return 'False'
    else:
        return 'Both'

categorized = df.groupby('CustID')['Condition'].apply(categorize)
categorized.value_counts()
Both     2
False    1
True     1
Name: Condition, dtype: int64