Combining two Series into a DataFrame in pandas
I think concat
is a nice way to do this. If they are present it uses the name attributes of the Series as the columns (otherwise it simply numbers them):
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
Note: This extends to more than 2 Series.
Pandas will automatically align these passed in series and create the joint indexThey happen to be the same here. reset_index
moves the index to a column.
In [2]: s1 = Series(randn(5),index=[1,2,4,5,6])In [4]: s2 = Series(randn(5),index=[1,2,4,5,6])In [8]: DataFrame(dict(s1 = s1, s2 = s2)).reset_index()Out[8]: index s1 s20 1 -0.176143 0.1286351 2 -1.286470 0.9084972 4 -0.995881 0.5280503 5 0.402241 0.4588704 6 0.380457 0.072251