Home > Net >  How fill NA with respect of another column?
How fill NA with respect of another column?

Time:11-25

I want to fill NaN values in this way: put the same values as the column B if they have the same value in B

Example:

A    B
nan 'ra'
9   'ra'
5   'pa'

So NaN value in column A should be 9 because they have the same values in column B.

CodePudding user response:

df['A'] = df.groupby('B')['A'].ffill().bfill()

Output:

>>> df
     A   B
0  9.0  ra
1  9.0  ra
2  5.0  pa
  • Related