Nathan Lloyd Nathan Lloyd - 10 days ago 7
Python Question

How to merge Series to DataFrame as columns, broadcasting

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

Answer

You could construct a dataframe from the series and then merge with the dataframe. So you specify the data as the values but multiply them by the length, set the columns to the index and set params for left_index and right_index to True:

In [27]:

df.merge(pd.DataFrame(data = [s.values] * len(s), columns = s.index), left_index=True, right_index=True)
Out[27]:
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

EDIT for the situation where you want the index of your constructed df from the series to use the index of the df then you can do the following:

df.merge(pd.DataFrame(data = [s.values] * len(df), columns = s.index, index=df.index), left_index=True, right_index=True)

This assumes that the indices match the length.

Comments