Sean
Sean

Reputation: 35

How to combine two pandas series which are differently indexed?

I try to combine two differently indexed series together (same number of rows). I tried pd.concat((s1, s2), axis=1). For example, s1 is:

index | s1
----- | -----
0     | 1.5
----- | -----
1     | 2

and s2 is:

index | s2
----- | -----
a     | 1
----- | -----
b     | 2

but I get:

index | s1  | s2  
----- | --- | --- 
0     | 1.5 | NaN
----- | --- | ---
1     | 2   | NaN
----- | --- | ---
a     | NaN | 1
----- | --- | ---
b     | NaN | 2

What I want is:

index | s1  | s2 
----- | --- | ---
a     | 1.5 | 1
----- | --- | ---
b     | 2   | 2

That is keep the index of series2. How could I get this? Many thanks!

Upvotes: 2

Views: 545

Answers (3)

piRSquared
piRSquared

Reputation: 294258

Option 1
pd.DataFrame.insert

s2.insert(0, 's1', s1.s1.values)
s2

    s1  s2
a  1.5   1
b  2.0   2

Option 2
Reconstruct

pd.DataFrame(dict(s1=s1.s1.values, s2=s2.s2.values), s2.index)

    s1  s2
a  1.5   1
b  2.0   2

Option 3
pd.DataFrame.join

s1.set_index(s2.index).join(s2)

    s1  s2
a  1.5   1
b  2.0   2

Upvotes: 2

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

You can set the index of s1 by s2's index and then concat them

s1 = pd.DataFrame({'s1':[1.5,2]},index=[0,1])
s2 = pd.DataFrame({'s2':[1,2]},index=['a','b'])
pd.concat([s2,s1.set_index(s2.index)],axis=1)

Output :

   s2   s1
a   1  1.5
b   2  2.0

or

pd.concat([s1.set_index(s2.index),s2],axis=1)
    s1  s2
a  1.5   1
b  2.0   2

Upvotes: 2

jezrael
jezrael

Reputation: 862641

Set index of s1 by s2 index first:

s1.index = s2.index
df = pd.concat([s1, s2], axis=1)
print (df)
    s1  s2
a  1.5   1
b  2.0   2

Upvotes: 4

Related Questions