@@ -724,30 +724,26 @@ either the left or right tables, the values in the joined table will be
724
724
labels = [' left' , ' right' ], vertical = False );
725
725
plt.close(' all' );
726
726
727
- To join a Series with a MultiIndex and a DataFrame, using the levels of the
728
- MultiIndex and columns from the DataFrame, transform the Series to a DataFrame
729
- using :meth: `Series.reset_index `.
727
+ You can merge a MultiIndex Series and a DataFrame, if the levels of
728
+ the MultiIndex correspond to the columns from the DataFrame. Transform
729
+ the Series to a DataFrame using :meth: `Series.reset_index ` before merging,
730
+ as shown in the following example.
730
731
731
732
.. ipython :: python
732
733
733
734
df = pd.DataFrame({" Let" : [" A" , " B" , " C" ], " Num" : [1 , 2 , 3 ]})
734
735
df
735
736
736
- # The series has a multi-index with levels corresponding to columns in
737
- # the DataFrame we want to merge with
738
- ser = pd.Series([' a' , ' b' , ' c' , ' d' , ' e' , ' f' ],
739
- index = pd.MultiIndex.from_arrays([[" A" , " B" , " C" ] * 2 ,
740
- [1 , 2 , 3 , 4 , 5 , 6 ]],
741
- names = [' Let' , ' Num' ])
742
- )
737
+ ser = pd.Series(
738
+ [" a" , " b" , " c" , " d" , " e" , " f" ],
739
+ index = pd.MultiIndex.from_arrays(
740
+ [[" A" , " B" , " C" ] * 2 , [1 , 2 , 3 , 4 , 5 , 6 ]], names = [" Let" , " Num" ]
741
+ ),
742
+ )
743
743
ser
744
744
745
- # Convert the Series to a DataFrame and merge
746
- df2 = pd.merge(df, ser.reset_index(), on = [' Let' , ' Num' ])
747
- type (df2)
745
+ pd.merge(df, ser.reset_index(), on = [' Let' , ' Num' ])
748
746
749
- # Now we merge the DataFrames
750
- pd.merge(df, df2, on = [' Let' , ' Num' ])
751
747
752
748
Here is another example with duplicate join keys in DataFrames:
753
749
0 commit comments