1

There are 2 columns in my Pandas dataframe.

cola    colb  
X         X     
C        NaN    
NaN       R     
X         X     

I want to get rid of cola and colb and replace it with colc.

cola    colb   colc
X         X     X
C        NaN    C
NaN       R     R
X         X     X

Basically I need to populate colc with the value in cola and colb. If there is a nan in cola then it will pull from colb and if there is a nan in colb it will pull from cola. cola and colb should always be equal if it doesn't have a nan in one of them.

How would I achieve this in pandas?

prettypython
  • 103
  • 1
  • 5

2 Answers2

3
df["colc"] = df["cola"].fillna(df["colb"])
Toby Petty
  • 4,431
  • 1
  • 17
  • 29
1

Alternatively, use np.where to create logical conditions to fill your array:

df["colc"] = np.where(df["cola"].notna(),df["cola"],df["colb"])
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69