Skip to content
Advertisement

Merging two non-overlapping pandas dataframe columns

I have a pandas dataframe with a pair of columns where, on every row, one cell is a nan and the other is not. It looks like this:

Var1 Var2
0 3 nan
1 8 nan
2 nan 6
3 4 nan
4 nan 2
5 nan 6

I would like to merge these two columns in one without the nans:

Var1
0 3
1 8
2 6
3 4
4 2
5 6

Any ideas?

Advertisement

Answer

Use fillna, setting values parameter to another Series.

df['Var1'].fillna(df['Var2'], inplace=True)
df['Var1']

#    Var1
# 0  3
# 1  8
# 2  6
# 3  4
# 4  2
# 5  6
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement