How to append a value in a new column to Null rows in Pandas

Viewed 45

Hello stackoverflow community

This is my sample data

Code      Sales   HeadQuarter
 CC       1000       XYZ
 AA       NaN        YYZ
 BB       2000       NaN
 DD       NaN        NaN

As I have to append a new column to respective rows that contains atleast one NaN value. The new column can contain any value. I'm using 1 as the value

The new table should look like this

Code       Sales        HeadQuarter   New_column
CC         1000           XYZ              
AA         NaN            YYZ            1
BB         2000           NaN            1
DD         NaN            NaN            1

Can anyone help me with this?

Thanks in Advance!

1 Answers

Test missing values and get at least on True per row for mask and create new column in DataFrame.loc:

df.loc[df.isna().any(axis=1), 'New_column'] = 1
print (df)
  Code   Sales HeadQuarter  New_column
0   CC  1000.0         XYZ         NaN
1   AA     NaN         YYZ         1.0
2   BB  2000.0         NaN         1.0
3   DD     NaN         NaN         1.0

If need set 2 values for match and not match use numpy.where:

df['New_column']  = np.where(df.isna().any(axis=1), 1, '')
print (df)
  Code   Sales HeadQuarter New_column
0   CC  1000.0         XYZ           
1   AA     NaN         YYZ          1
2   BB  2000.0         NaN          1
3   DD     NaN         NaN          1
Related