[英]Applying a pandas GroupBy with mixed boolean and numerical values
[英]Groupby values using boolean in pandas
df['check'] = ((df['id'] == 123) & (df['date1'] >= date1)) | ((df['id'] == 456) & (df['date2'] >= date2))
present = df.groupby(['id', 'month', 'check'])['userid'].nunique().reset_index(name="usercount")
這是我的代碼,因此我的預期輸出必須在按id
分組的usercount
列中usercount
每月唯一用戶數。 我使用了id
、 month
和check
in groupby
。
check
列的類型為bool
,基於我的代碼的第一行,但是當我從present
數據幀獲得輸出時,將計算check
值為True
的用戶,也計算具有False
。
實際上,它應該計算check
列中只有True
的用戶。
幫我解決這個問題
您需要通過boolean indexing
按check
列過濾,而不是通過groupby
by
參數傳遞:
#first convert datetimes to start of months
df['month'] = df['month'].dt.floor('d') - pd.offsets.MonthBegin(1)
print (df)
check month id userid
0 True 2019-06-01 123 a
1 False 2019-02-01 123 b
2 False 2019-01-01 123 c
3 False 2019-02-01 123 d
4 True 2019-06-01 123 e
5 True 2020-07-01 123 f
6 True 2020-07-01 123 g
7 True 2020-06-01 123 h
print (df[df['check']])
check month id userid
0 True 2019-06-01 123 a
4 True 2019-06-01 123 e
5 True 2020-07-01 123 f
6 True 2020-07-01 123 g
7 True 2020-06-01 123 h
present = (df[df['check']].groupby(['id', 'month'])['userid']
.nunique()
.reset_index(name="usercount"))
print (present)
id month usercount
0 123 2019-06-01 2
1 123 2020-06-01 1
2 123 2020-07-01 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.