简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM