Esther
Esther

Reputation: 49

How to add a value to a column based on specific column values in pandas

I have a Dataframe that looks like this:

Name      Owner    Date         Total
Asun      Louise   14/02/2020    75
Rodrigo   Matt     11/02/2020    67
Asun      Louise   10/20/2020    nan

I would like the dataframe to have the same value in the Total column.

Name      Owner    Date         Total
Asun      Louise   14/02/2020    75
Rodrigo   Matt     11/02/2020    67
Asun      Louise   10/20/2020    75

I got really stuck with this. Anyone knows how to do this?

Upvotes: 0

Views: 31

Answers (1)

jezrael
jezrael

Reputation: 862511

Use GroupBy.transform with GroupBy.first for first non missing value per groups and repalce missing values of Total column by it with Series.fillna:

df['Total'] = df['Total'].fillna(df.groupby(['Name','Owner'])['Total'].transform('first'))
print (df)
      Name   Owner        Date  Total
0     Asun  Louise  14/02/2020   75.0
1  Rodrigo    Matt  11/02/2020   67.0
2     Asun  Louise  10/20/2020   75.0

Upvotes: 1

Related Questions