How fill NA with respect of another column?

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.

>Solution :

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

Output:

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

Leave a Reply