TayyabRahmani
TayyabRahmani

Reputation: 123

Add one column after groupby function

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

Answers (2)

tawab_shakeel
tawab_shakeel

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

yatu
yatu

Reputation: 88305

You could GroupBy the X column, aggregate with the cumcount and add P as a prefix:

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

Upvotes: 4

Related Questions