我有以下样本集。
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()
Condition
True 3
False 3
但是如何获得符合这两个条件的唯一ID呢? e.g。
Condition
True 3
False 3
Both 2
答案 0 :(得分:2)
不确定这是否是最多" pandas"方式,但您可以使用set
来比较每个分区中的用户(Python set
数据结构是一个哈希表,它将自动丢弃重复项):
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)
答案 1 :(得分:1)
我建议对CustID
进行分组。然后,我们可以查看每个组,并轻松确定每个唯一ID是仅True
,仅False
还是两者。然后我们只使用Series.value_counts()
:
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