Back
I have two Series s1 and s2 with the same (non-consecutive) indices. How do I combine s1 and s2 to being two columns in a DataFrame and keep one of the indices as a third column?
You can simply use concat and it will give you the desired result:
In [1]: s1 = pd.Series([1, 2], index=['A', 'B'], name='s1')In [2]: s2 = pd.Series([3, 4], index=['A', 'B'], name='s2')In [3]: pd.concat([s1, s2], axis=1)Out[3]: s1 s2A 1 3B 2 4In [4]: pd.concat([s1, s2], axis=1).reset_index()Out[4]: index s1 s20 A 1 31 B 2 4
In [1]: s1 = pd.Series([1, 2], index=['A', 'B'], name='s1')
In [2]: s2 = pd.Series([3, 4], index=['A', 'B'], name='s2')
In [3]: pd.concat([s1, s2], axis=1)
Out[3]:
s1 s2
A 1 3
B 2 4
In [4]: pd.concat([s1, s2], axis=1).reset_index()
Out[4]:
index s1 s2
0 A 1 3
1 B 2 4
Pandas will automatically align these passed in series and create the joint index They happen to be the same here. reset_index moves the index to a column.
s1 = Series(randn(5),index=[1,2,4,5,6]) s2 = Series(randn(5),index=[1,2,4,5,6]) DataFrame(dict(s1 = s1, s2 = s2)).reset_index()
s1 = Series(randn(5),index=[1,2,4,5,6])
s2 = Series(randn(5),index=[1,2,4,5,6])
DataFrame(dict(s1 = s1, s2 = s2)).reset_index()
31k questions
32.8k answers
501 comments
693 users