1

I have two columns containing strings and NAs and I want to combine them into 1. I feel this should be fairly simple but cannot seem to get it to work or find the answer on here. Below is the result I am after.

S1  S2  S
A   Nan A
A   Nan A
A   Nan A
A   Nan A
Nan C   C
Nan C   C
Nan C   C
Nan C   C
Nan Nan Nan
Nan Nan Nan
Nan Nan Nan
B   Nan B
B   Nan B
B   Nan B
B   Nan B
B   Nan B

I thought df['S'] = df['S1']+ df['S2'] would work but no.

Really feel like there will be an obvious fix, thanks in advance.

ar1847
  • 37
  • 6

1 Answers1

1

Use combine_first:

df['S_new'] = df['S1'].combine_first(df['S2'])
print (df)
     S1   S2    S S_new
0     A  NaN    A     A
1     A  NaN    A     A
2     A  NaN    A     A
3     A  NaN    A     A
4   NaN    C    C     C
5   NaN    C    C     C
6   NaN    C    C     C
7   NaN    C    C     C
8   NaN  NaN  NaN   NaN
9   NaN  NaN  NaN   NaN
10  NaN  NaN  NaN   NaN
11    B  NaN    B     B
12    B  NaN    B     B
13    B  NaN    B     B
14    B  NaN    B     B
15    B  NaN    B     B
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252