Skip to content

Commit 72cb9da

Browse files
committed
Add example in docs for multiindex series and dataframe merge
1 parent 7b0887c commit 72cb9da

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

doc/source/user_guide/merging.rst

+23
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,10 @@ either the left or right tables, the values in the joined table will be
716716
717717
result = pd.merge(left, right, how='inner', on=['key1', 'key2'])
718718
719+
To join a Series with a MultiIndex and a DataFrame, using the levels of the
720+
MultiIndex and columns from the DataFrame, transform the Series to a DataFrame
721+
using :meth:`Series.reset_index`.
722+
719723
.. ipython:: python
720724
:suppress:
721725
@@ -724,6 +728,25 @@ either the left or right tables, the values in the joined table will be
724728
labels=['left', 'right'], vertical=False);
725729
plt.close('all');
726730
731+
.. ipython:: python
732+
733+
df = pd.DataFrame({"Let": ["A", "B", "C"], "Num": [1, 2, 3]})
734+
df
735+
736+
# The series has a multi-index with levels corresponding to columns in the DataFrame we want to merge with
737+
ser = pd.Series(
738+
['a', 'b', 'c', 'd', 'e', 'f'],
739+
index=pd.MultiIndex.from_arrays([["A", "B", "C"] * 2, [1, 2, 3, 4, 5, 6]], names=['Let', 'Num']
740+
)
741+
ser
742+
743+
# Convert the Series to a DataFrame and merge
744+
pd.merge(df, ser.reset_index(), on=['Let', 'Num'])
745+
type(df2)
746+
747+
# Now we merge the DataFrames
748+
pd.merge(df, df2, on=['Let', 'Num'])
749+
727750
Here is another example with duplicate join keys in DataFrames:
728751
729752
.. ipython:: python

0 commit comments

Comments
 (0)