filling null cells with specific values in a dataframe

Viewed 22

Assume we have the following dataframe

date = '20/09/2022'


A         B

n.a.       15/02/2022
0.74       15/02/2022
0.3        ''
1          ''
1          15/02/2022
n.a.       ''

and we want to do the following:

  • if the value in A column is equal to 1 then fill the B column with n.a.
  • if the value in A column is smaller than 1 or 'n.a'.
    THEN
  • IF The B column is empty --> insert the variable date in that cell
  • If The B column is NOT empty -->keep the value that it already has

thus our example should become the following

A         B
n.a.       15/02/2022
0.74       15/02/2022
0.3        20/09/2022
1          'n.a.'
1          'n.a.'
n.a        20/09/2022
1 Answers

You can use boolean indexing:

date = '20/09/2022'

m1 = pd.to_numeric(df['A'], errors='coerce').eq(1)
m2 = df['B'].replace('', pd.NA).isna() # or df['B'].eq('')

df.loc[m1, 'B'] = 'n.a.'
df.loc[m2&~m1, 'B'] = date

output:

      A           B
0  n.a.  15/02/2022
1  0.74  15/02/2022
2   0.3  20/09/2022
3     1        n.a.
4     1        n.a.
5  n.a.  20/09/2022
Related