cegarza
cegarza

Reputation: 135

Append Dataframe to previously existing MultiIndex DataFrame

Suppose I have a MultiIndex DataFrame that looks as such:

           C1   C2    C3
A1   B1
     B2
A2   B1
     B2

How can I append the following dataframe:

      C1   C2    C3
B3
B4
B5
B6

underneath A1 so that the final product looks like this:

           C1   C2    C3
A1   B1
     B2
     B3
     B4
     B5
     B6
A2   B1
     B2

Upvotes: 0

Views: 68

Answers (1)

Roshan Santhosh
Roshan Santhosh

Reputation: 687

You will have to reset the indices of both the dataframes and then merge them, before setting the multi-index again.

For my example, my index names are cp_name and products, original multi-index dataframe is d and single index dataframe is temp.


#Setting the second index as a variable in the single-index dataframe
temp['cp_name'] = 'A'

#Resetting the indices
d_ = d.reset_index()
temp_ = temp.reset_index()

out = pd.concat([d_, temp_])


out.sort_values(['cp_name','products']).set_index(['cp_name','products'])

Original Datasets :


                  le_id  run_seq  cp_id  tran_amnt currency  current
cp_name products                                                    
A       U           101        1    201        100      USD    201.0
B       U           102        1    202        200      USD      NaN
        V           103        1    202        672      INR      NaN
          le_id  run_seq  cp_id cp_name  tran_amnt currency current
products                                                           
X           104        3    205       E        437      SGD     NaN
V           102        3    203       C        783      INR     NaN

Final output

                  cp_id currency current  le_id  run_seq  tran_amnt
cp_name products                                                   
A       U           201      USD     201    101        1        100
        V           203      INR     NaN    102        3        783
        X           205      SGD     NaN    104        3        437
B       U           202      USD     NaN    102        1        200
        V           202      INR     NaN    103        1        672

Upvotes: 1

Related Questions