Home > database >  Replace NaN with column value on a row by row basis
Replace NaN with column value on a row by row basis

Time:03-01

In my Pandas DataFrame I'd like to replace all instances of NaN (np.nan) on a row by row basis with the corresponding value from column "E".

This DataFrame here..

A B C D E
1 NaN 3 NaN 88
NaN 5 NaN 4 55

should result in..

A B C D E
1 88 3 88 88
55 5 55 4 55

I cannot find any code to solve this issue.

Data:

{'A': [1, nan],
 'B': [nan, 5],
 'C': [3, nan],
 'D': [nan, 4],
 'E': [88, 55]}

CodePudding user response:

Let us try mask

df = df.mask(df.isna(),df['E'],axis=0)
Out[423]: 
      A     B     C     D   E
0   1.0  88.0   3.0  88.0  88
1  55.0   5.0  55.0   4.0  55

CodePudding user response:

You could transpose fillna transpose back:

df = df.T.fillna(df['E']).T.astype(int)

Output:

    A   B   C   D   E
0   1  88   3  88  88
1  55   5  55   4  55
  • Related