Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge a Series and DataFrame

If you came here looking for information on how to merge a DataFrame and Series on the index, please look at this answer.

The OP's original intention was to ask how to assign series elements as columns to another DataFrame. If you are interested in knowing the answer to this, look at the accepted answer by EdChum.


Best I can come up with is

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})  # see EDIT below s = pd.Series({'s1':5, 's2':6})  for name in s.index:     df[name] = s[name]     a  b  s1  s2 0  1  3   5   6 1  2  4   5   6 

Can anybody suggest better syntax / faster method?

My attempts:

df.merge(s) AttributeError: 'Series' object has no attribute 'columns' 

and

df.join(s) ValueError: Other Series must have a name 

EDIT The first two answers posted highlighted a problem with my question, so please use the following to construct df:

df = pd.DataFrame({'a':[np.nan, 2, 3], 'b':[4, 5, 6]}, index=[3, 5, 6]) 

with the final result

    a  b  s1  s2 3 NaN  4   5   6 5   2  5   5   6 6   3  6   5   6 
like image 391
Nathan Lloyd Avatar asked Oct 08 '14 20:10

Nathan Lloyd


People also ask

Can you merge a series and a DataFrame?

Combine Two Series Using pandas.merge() can be used for all database join operations between DataFrame or named series objects. You have to pass an extra parameter “name” to the series in this case. For instance, pd. merge(S1, S2, right_index=True, left_index=True) .

Can you append a series to a DataFrame?

Appending a multiple rows - Appending a list of Dictionaries to a DataFrame. You can also pass a list of Series or a list of Dictionaries to append multiple rows.


1 Answers

Update
From v0.24.0 onwards, you can merge on DataFrame and Series as long as the Series is named.

df.merge(s.rename('new'), left_index=True, right_index=True) # If series is already named, # df.merge(s, left_index=True, right_index=True) 

Nowadays, you can simply convert the Series to a DataFrame with to_frame(). So (if joining on index):

df.merge(s.to_frame(), left_index=True, right_index=True) 
like image 195
Nicholas Morley Avatar answered Sep 18 '22 18:09

Nicholas Morley