如何根据另一列的NaN值在pandas数据帧中设置值?

时间:2016-06-22 08:39:20

标签: python python-2.7 pandas nan

我的数据框名为df,原始形状为(4361, 15)。一些agefm列的值是NaN。看看:

> df[df.agefm.isnull() == True].agefm.shape
(2282,)

然后我创建新列并将其所有值设置为0:

df['nevermarr'] = 0

所以我想将nevermarr值设置为1,然后在那一行agefm是Nan:

df[df.agefm.isnull() == True].nevermarr = 1

没有任何改变:

> df['nevermarr'].sum()
0

我做错了什么?

1 个答案:

答案 0 :(得分:3)

最好的是使用numpy.where

df['nevermarr'] = np.where(df.agefm.isnull(), 1, 0)
print (df)
   agefm  nevermarr
0    NaN          1
1    5.0          0
2    6.0          0

或者使用loc==True可以省略:

df.loc[df.agefm.isnull(), 'nevermarr'] = 1

mask

df['nevermarr'] = df.nevermarr.mask(df.agefm.isnull(), 1)
print (df)
   agefm  nevermarr
0    NaN          1
1    5.0          2
2    6.0          3

样品:

import pandas as pd
import numpy as np

df = pd.DataFrame({'nevermarr':[7,2,3],
                   'agefm':[np.nan,5,6]})

print (df)
   agefm  nevermarr
0    NaN          7
1    5.0          2
2    6.0          3

df.loc[df.agefm.isnull(), 'nevermarr'] = 1
print (df)
   agefm  nevermarr
0    NaN          1
1    5.0          2
2    6.0          3