Skip to content

Commit 31bb36a

Browse files
author
pdpark
committed
Doc: Adds example of joining a series to a dataframe.
Resolves: pandas-dev#12550
1 parent 0477880 commit 31bb36a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

doc/source/merging.rst

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

0 commit comments

Comments
 (0)