twhale
twhale

Reputation: 755

How to combine two Series with the same index in python?

I have two Series (df1 and df2) of equal length, which need to be combined into one DataFrame column as follows. Each index has only one value or no values but never two values, so there are no duplicates (e.g. if df1 has a value 'A' at index 0, then df2 is empty at index 0, and vice versa).

df1 =    c1      df2 =    c2
      0  A             0 
      1  B             1
      2                2  C
      3  D             3
      4  E             4
      5                5  F
      6                6
      7  G             7

The result I want is this:

      0  A
      1  B
      2  C
      3  D
      4  E
      5  F
      6
      7  G

I have tried .concat, .append and .union, but these do not produce the desired result. What is the correct approach then?

Upvotes: 1

Views: 922

Answers (2)

jpp
jpp

Reputation: 164613

For an in-place solution, I recommend pd.Series.replace:

df1['c1'].replace('', df2['c2'], inplace=True)

print(df1)

  c1
0  A
1  B
2  C
3  D
4  E
5  F
6   
7  G

Upvotes: 0

Joe
Joe

Reputation: 12417

You can try so:

df1['new'] = df1['c1'] + df2['c2']

Upvotes: 5

Related Questions