I have dataframe named df
with original shape (4361, 15)
. Some of agefm
column`s values are NaN. Just look:
> df[df.a
The best is use 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
Or use loc, ==True
can be omitted:
df.loc[df.agefm.isnull(), 'nevermarr'] = 1
Or 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
Sample:
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