我有一个包含三列的数据框(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
非常感谢您的帮助!
(df.assign(unique_investor2=df.groupby(['ID', 'Round'])['Unique Investor'].apply(pd.Series.drop_duplicates).droplevel([0,1])) .groupby('ID')['unique_investor2'].cumsum().ffill(downcast='infer') )
- SeaBean