[英]Python pandas: How to group by and count unique values based on multiple columns?
[英]Python: Group and count unique variables based on multiple grouping without recount
我有一個包含 3 列的 Dataframe:
ID Round Investor
X 1 A
X 2 A
X 2 B
X 3 A
Y 1 A
Y 1 B
Y 1 C
Y 2 B
Y 2 D
並且想為每個ID統計每一輪的獨立投資者的數量。 但我不希望它重新計算投資者是否在上一輪。 我使用的代碼是:
print(df.groupby(['ID', 'Round'])['Investor'].nunique())
結果是:
ID Round Unique Investor
X 1 1
2 2
2 2
3 1
Y 1 3
1 3
1 3
2 2
2 2
但是當投資者為相同的 ID 投資了較早的一輪時,我不知道這算什么:
ID Round Unique Investor
X 1 1
2 1
2 1
3 0
Y 1 3
1 3
1 3
2 1
2 1
任何幫助是極大的贊賞!
您可以定義一個幫助列Investor2
,它在ID
下分組,並使用Series.drop_duplicates
在同一ID
中刪除重復項
然后,像之前使用.transform()
和nunique
在此Investor2
列上所做的那樣,按ID
和Round
分組,如下所示:
df['Unique Investor'] = (
df.assign(Investor2=df.groupby('ID')['Investor'].apply(pd.Series.drop_duplicates).droplevel(0))
.groupby(['ID', 'Round'])['Investor2'].transform('nunique')
)
結果:
print(df)
ID Round Investor Unique Investor
0 X 1 A 1
1 X 2 A 1
2 X 2 B 1
3 X 3 A 0
4 Y 1 A 3
5 Y 1 B 3
6 Y 1 C 3
7 Y 2 B 1
8 Y 2 D 1
一種可能的解決方案是根據“ID”和 Investor、groupby ID 和 Round 刪除重復項以獲得唯一數量,並將結果合並回主 dataframe:
dups = ['ID', 'Investor']
group = ['ID', 'Round']
mapping = (df.drop_duplicates(subset = dups)
.groupby(group)
.Investor
.nunique()
)
(df.filter(group)
.merge(mapping, left_on = group,
right_index = True, how = 'left')
.fillna(0, downcast='infer')
)
ID Round Investor
0 X 1 1
1 X 2 1
2 X 2 1
3 X 3 0
4 Y 1 3
5 Y 1 3
6 Y 1 3
7 Y 2 1
8 Y 2 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.