Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two Series into a DataFrame in pandas

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?

like image 918
user7289 Avatar asked Aug 05 '13 15:08

user7289


People also ask

Can you append series to DataFrame?

append() Pandas DataFrame. append() will append rows (add rows) of other DataFrame, Series, Dictionary or list of these to another DataFrame.


1 Answers

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  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 

Note: This extends to more than 2 Series.

like image 125
Andy Hayden Avatar answered Oct 02 '22 20:10

Andy Hayden