Skip to content

Commit e239981

Browse files
author
pdpark
committed
Doc: Add example of merging a Series with a DataFrame
Resolves: pandas-dev#12550
1 parent e212e78 commit e239981

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

doc/source/merging.rst

+26
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,32 @@ either the left or right tables, the values in the joined table will be
712712
labels=['left', 'right'], vertical=False);
713713
plt.close('all');
714714
715+
To join a Series and a DataFrame, the Series has to be transformed into a DataFrame first:
716+
717+
.. ipython:: python
718+
719+
df = pd.DataFrame({"Let": ["A", "B", "C"], "Num": [1, 2, 3]})
720+
df
721+
722+
# The series has a multi-index with levels corresponding to columns in the DataFrame we want to merge with
723+
ser = pd.Series(
724+
['a', 'b', 'c', 'd', 'e', 'f'],
725+
index=pd.MultiIndex.from_arrays([["A", "B", "C"]*2, [1, 2, 3, 4, 5, 6]])
726+
)
727+
ser
728+
729+
# Name the row index levels
730+
ser.index.names=['Let','Num']
731+
ser
732+
733+
# reset_index turns the multi-level row index into columns, which requires a DataFrame
734+
df2 = ser.reset_index()
735+
type(df2)
736+
737+
# Now we merge the DataFrames
738+
pd.merge(df, df2, on=['Let','Num'])
739+
740+
715741
Here is another example with duplicate join keys in DataFrames:
716742

717743
.. ipython:: python

0 commit comments

Comments
 (0)