hdatas
hdatas

Reputation: 1082

Create column based on condition

I have this dataset:

        Players       Material_bough
1         X1                Wood
2         X2                Iron
3         X1                Stone

I would like to create a new column that shows the sum of materials a player bought.

        Players       Material_bough         Material_total
1         X1                Wood                  2
2         X2                Iron                  1
3         X1                Stone                 2

As Wood + Stone = 2 materials.

I think I should use groupby but don't know how.

Upvotes: 1

Views: 67

Answers (1)

jezrael
jezrael

Reputation: 863501

I think it is same as count Players without aggregating by transform:

df['Material_total'] = df.groupby('Players')['Material_bough'].transform('size')

Or:

df['Material_total'] = df.groupby('Players')['Material_bough'].transform('count')

Upvotes: 2

Related Questions