简体   繁体   中英

How can I fill null values in one column according to another column in pandas dataframe?

Long story short, I have a dataframe contains two columns passenger_title and passenger_gender. I need to replace null values in passenger_gender column with specific values according to the passenger_title column.

Let's say the passenger_title is MISTER and passenger_gender is NaN. I've tried to run the codes below. They both worked but didn't replace.

test.loc[test['passenger_title'] == 'MISTER', 'passenger_gender'].fillna('M', inplace = True)

I also tried this code below

df[(pd.isnull(df['passenger_gender'])) & (df['passenger_title'] == 'MISTER')].loc[:, 'passenger_gender'] = 'M'

What would be your suggestion? Thanks in advance. Stay healthy!

I would use np.where()

 df['passenger_gender'] = np.where((df['passenger_title'] == 'MISTER') & (df['passenger_gender'].isnull()), 'M', df['passenger_gender'])

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