[英]create new column of incremental number based on 2 categorical columns pandas dataframe
我有一個熊貓數據框,其中包含username
和phase
列。 我想用增量值創建一個名為count
的單獨列。
count
將基於username
在特定phase
出現的次數。 我怎樣才能有效地做到這一點? 任何建議表示贊賞。
username phase count
0 andrew 1 1
1 andrew 1 2
2 alex 1 1
3 alex 2 1
4 andrew 1 3
5 cindy 3 1
6 alex 2 2
您可以在username
和phase
的 groupby 之后使用cumcount
。
df['count'] = df.groupby(['username', 'phase']).cumcount()+1
print(df)
username phase count
0 andrew 1 1
1 andrew 1 2
2 alex 1 1
3 alex 2 1
4 andrew 1 3
5 cindy 3 1
6 alex 2 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.