简体   繁体   中英

Conditional fillna() in pandas dataframe

I have two below dataframes df1 and df2

df1:

A   B       C       D
1   Nora    NaN     Japan
2   Neo     NaN     India
3   Nord    NaN     Fuji
4   Noman   2020    Unknown

df2:

E       F
1123    Neo
1124    Norm
1126    Nora

I need to perform a fillna in df1 and take values from df2 only for those values which have entries in df2 .

Resultant Dataframe: df1:

A   B       C       D
1   Nora    1126    Japan
2   Neo     1123    India
3   Nord    NaN     Fuji
4   Noman   2020    Unknown

Is there any way for the same? I do not want to loop since I have huge dataframe which might decrease the performance of the code.

You can set column F as index in second df2 then use that as mapping using pd.Series.map then use it as fill value.

mapping = df2.set_index('F').squeeze()
df1['C'] = df1['C'].fillna(df['B'].map(mapping))

   A      B       C        D
0  1   Nora  1126.0    Japan
1  2    Neo  1123.0    India
2  3   Nord     NaN     Fuji
3  4  Noman  2020.0  Unknown

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