Jacopo Fasolo
Jacopo Fasolo

Reputation: 23

Filling NaN values with values that are not NaN using Python Pandas

I have a dataframe that have 2 columns with some NaN values in both columns.

df = { 'A' : [1,Nan, 2, Nan, Nan, 3],
       'B' : [Nan, Nan, 3, 4, 5 ,Nan]}

I would like to fill NaN values in column A with only not NaN values in column B and vice versa. The result should be like:

df = { 'A': [1,Nan, 2, 4, 5, 3],
       'B' : [1, Nan, 3, 4, 5 ,3]}

Thanks

Upvotes: 2

Views: 62

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Use, bfill and ffill with axis parameter equal to 1:

df.ffill(1).bfill(1)

Output:

     A    B
0  1.0  1.0
1  NaN  NaN
2  2.0  3.0
3  4.0  4.0
4  5.0  5.0
5  3.0  3.0

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

This is one approach using df.fillna

Demo:

import pandas as pd
import numpy as np
df = { 'A' : [1,np.nan, 2, np.nan, np.nan, 3],
       'B' : [np.nan, np.nan, 3, 4, 5 ,np.nan]}
df = pd.DataFrame(df)
df["A"] = df["A"].fillna(df["B"])
df["B"] = df["B"].fillna(df["A"])
print(df)

Output:

     A    B
0  1.0  1.0
1  NaN  NaN
2  2.0  3.0
3  4.0  4.0
4  5.0  5.0
5  3.0  3.0

Upvotes: 1

Related Questions