简体   繁体   中英

Python Function to fill nan values based on another column

I have a dataset like this

Ticket    Cabin
123       Nan
162       B14
123       C12
122       D13
162       Nan
122       Nan

So I want to fill Nan values based on Ticket values such as the result is

Ticket    Cabin
123       C12
162       B14
123       C12
122       D13
162       B14
122       D13

Is there any function or way we could do this?

Create a mapping of tickets to non-null Cabin values, then use this to backfill other rows:

df['Cabin_Filled'] = df['Ticket'].map(df.groupby('Ticket')['Cabin'].first())
df

   Ticket Cabin Cabin_Filled
0     123   NaN          C12
1     162   B14          B14
2     123   C12          C12
3     122   D13          D13
4     162   NaN          B14
5     122   NaN          D13

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