我有一个名为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


我究竟做错了什么?

最佳答案

最好是使用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

关于python - 如何基于另一列的NaN值设置 Pandas 数据框中的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37962759/

10-12 23:12