簡體   English   中英

基於2個分類列pandas數據框創建新的增量列

[英]create new column of incremental number based on 2 categorical columns pandas dataframe

我有一個熊貓數據框,其中包含usernamephase列。 我想用增量值創建一個名為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


您可以在usernamephase的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM