简体   繁体   中英

How to substitute NaN values of a column based on the values of another column?

I want to substitute NaN values of column Title based on the values of column Idx. If Idx is equal to 1, then NaN must be substituted by 0, if Idx is equal to 0, then NaN Title must be equal to 1.

Title   Idx
NaN     0
0       1
1       0
NaN     0
NaN     1

I tried this:

df.loc[df['Title'].isnull(), 'Title'] = 0

But of course it always puts 0. How can I add the condition here?

You can pass any Series or column to fillna() . In this case you need to fill the missing values with the Series 1 - df['Idx'] to get the result:

>>> df
   Title  Idx
0    NaN    0
1      0    1
2      1    0
3    NaN    0
4    NaN    1

>>> df['Title'] = df['Title'].fillna(1 - df['Idx'])
>>> df
   Title  Idx
0      1    0
1      0    1
2      1    0
3      1    0
4      0    1

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