Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join a Series to a DataFrame?

Is there any way to join a Series to a DataFrame directly?

The join would be on a field of the dataframe and on the index of the series.

The only way I found was to convert the series to a dataframe first, as in the code below.

import numpy as np
import pandas as pd

df = pd.DataFrame()
df['a'] = np.arange(0, 4)
df['b'] = np.arange(100, 104)


s = pd.Series(data=np.arange(100, 103))

# this doesn't work
# myjoin = pd.merge(df, s, how='left', left_on='a', right_index=True)

# this does
s = s.reset_index()
# s becomes a Dataframe
# note you cannot reset the index of a series inplace
myjoin = pd.merge(df, s, how='left', left_on='a', right_on='index')

print myjoin
like image 420
Pythonista anonymous Avatar asked Sep 01 '15 15:09

Pythonista anonymous


1 Answers

I guess http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html might help.

For example inner/outer join.

pd.concat((df,s), axis=1)
Out[26]: 
   a    b    0
0  0  100  100
1  1  101  101
2  2  102  102
3  3  103  NaN

In [27]: pd.concat((df,s), axis=1, join='inner')
Out[27]: 
   a    b    0
0  0  100  100
1  1  101  101
2  2  102  102
like image 53
Alex Avatar answered Sep 28 '22 22:09

Alex