Reputation: 123
I want to add a column according to the following condition.
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]})
Expected Output:
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
Upvotes: 3
Views: 77
Reputation: 3749
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
Upvotes: 1