3

how to fill null values in a row based on the value in another column.

A  B
0  5 
1  NAN
1  6
0  NAN

for the null value in B if coressponding value in A is 0 then fill with the previous value.

A  B
0  5 
1  NAN
1  6
0  6

```

it want it to be like this
sentence
  • 8,213
  • 4
  • 31
  • 40
chink
  • 1,505
  • 3
  • 28
  • 70
  • Possible duplicate of [Pandas fill missing values in dataframe from another dataframe](https://stackoverflow.com/questions/29357379/pandas-fill-missing-values-in-dataframe-from-another-dataframe) – Michael Heidelberg Apr 18 '19 at 16:58
  • @MichaelHeidelberg that question asks about fill null values based on a common index, not based on a condition on another column and the previous value. – user3483203 Apr 18 '19 at 17:00

3 Answers3

3

numpy.where + isnull + ffill

df.assign(
    B=np.where(df.A.eq(0) & df.B.isnull(), df.B.ffill(), df.B)
)

   A    B
0  0  5.0
1  1  NaN
2  1  6.0
3  0  6.0
user3483203
  • 50,081
  • 9
  • 65
  • 94
1

Another way using loc,

df.loc[df['A'].eq(0), 'B'] = df['B'].ffill()

    A   B
0   0   5
1   1   NaN
2   1   6
3   0   6
Vaishali
  • 37,545
  • 5
  • 58
  • 86
1

A faster way (compared to the previous ones):

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[0,1,1,0], 'B':[5,np.nan,6,np.nan]})

df.B = np.where(df.A==0, df.B.ffill(), df.B)

and you get:

    A   B
0   0   5.0
1   1   NaN
2   1   6.0
3   0   6.0
sentence
  • 8,213
  • 4
  • 31
  • 40