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

蹲街弑〆低调 提交于 2019-12-24 16:14:08

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/32920408/how-to-substitute-nan-values-of-a-column-based-on-the-values-of-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!