How to fill names with NA based on a different column

Viewed 46

How can I fill the second column with NaN if the first column has NaN?

I tried this

df1.type2.fillna(value=df1.type1, inplace=True)

input

,type1,type2
2020-01-02 6:00,NaN,ABC
2020-01-02 12:00,NaN,DEF
2020-01-02 18:00,60,GHI

output

,type1,type2
2020-01-02 6:00,NaN,NaN
2020-01-02 12:00,NaN,NaN
2020-01-02 18:00,60,GHI
2 Answers

Use DataFrame.loc with Series.isna:

df.loc[df.type1.isna(), 'type2'] = np.nan

Or Series.mask with default value NaN, so not necessary set:

df['type2'] = df['type2'].mask(df.type1.isna())
print (df)
                  type1 type2
2020-01-02 6:00     NaN   NaN
2020-01-02 12:00    NaN   NaN
2020-01-02 18:00   60.0   GHI

you can also use pandas.DataFrame.where

>>> df.type2.where(df.type1.notna(),inplace=True)
>>> df
         Unnamed: 0  type1 type2
0   2020-01-02 6:00    NaN   NaN
1  2020-01-02 12:00    NaN   NaN
2  2020-01-02 18:00   60.0   GHI
Related