[英]How to add one column according to the order after `groupby` in pandas?
[英]Add one column after groupby function
我想根據以下條件添加列。
df = pd.DataFrame({'X' : ['M1', 'M1', 'M1', 'M2', 'M2', 'M3', 'M4', 'M4', 'M4', 'M4'], 'Total': [1,2,3,21,15,42,1,2,25,4]})
預期產出:
X Total P
M1 1 P1
M1 2 P2
M1 3 P3
M2 21 P1
M2 15 P2
M3 42 P1
M4 1 P1
M4 2 P2
M4 25 P3
M4 4 P4
您可以GroupBy
X
列,與cumcount
聚合並添加P
作為前綴:
df['P'] = 'P'+df.groupby('X').cumcount().add(1).astype(str)
X Total P
0 M1 1 P1
1 M1 2 P2
2 M1 3 P3
3 M2 21 P1
4 M2 15 P2
5 M3 42 P1
6 M4 1 P1
7 M4 2 P2
8 M4 25 P3
9 M4 4 P4
df['P'] = df.groupby(['X'])['Total'].agg({"p":"cumcount"})+1
df['P'] = 'P'+df['p'].astype(str)
print(df)
X Total P
0 M1 1 P1
1 M1 2 P2
2 M1 3 P3
3 M2 21 P1
4 M2 15 P2
5 M3 42 P1
6 M4 1 P1
7 M4 2 P2
8 M4 25 P3
9 M4 4 P4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.