Search code examples
pythonpandasconcatenationmulti-index

Concat DataFrame to multi index df keeping original multi index


I have 2 dataframes from a budgeting finances project, one df of the recorded spending;

                          Food  Clothes  Bills  Social  Travel  Art  Other  Daily Total
Week End   Today's Date
2020-09-27 2020-09-21     25       25     25      25      25   25     25          175
           2020-09-23     20       20     20      20      20   20     20          140
           2020-09-24     12       12     12      12      12   12     12           84
           2020-09-25     20       20     20      20      20   20     20          140

And one of the weekly total's;

     Food  Clothes  Bills  Social  Travel  Art  Other  Daily Total
0    77       77     77      77      77   77     77          539

I'd like to concat them whilst keeping the original multi index to look like this;

                          Food  Clothes  Bills  Social  Travel  Art  Other  Daily Total
Week End   Today's Date
2020-09-27 2020-09-21     25       25     25      25      25   25     25          175
           2020-09-23     20       20     20      20      20   20     20          140
           2020-09-24     12       12     12      12      12   12     12           84
           2020-09-25     20       20     20      20      20   20     20          140
                0         77       77     77      77      77   77     77          539

If I do a basic concat function the multi index turns into a bunch of tuples like;

                                              Food  Clothes  Bills  Social

(2020-09-27 00:00:00, 2020-09-21 00:00:00)     25       25     25      25 
etc.

 

Any ideas?? Fairly new to pandas and coding in general so any help would be much appreciated.


Solution

  • I changed the column titles to make them easier to work with. Week End = Week_End Today's Date = Todays_Date Daily_Total

    You can just append the row

    df2 contains your weekly totals

    #set an index to match your recorded spending df
    df2['Week_End'] = '2020-09-27'
    df2['Todays_Date'] = '0'
    df2.set_index(['Week_End', 'Todays_Date'], inplace=True)
    
    
    #append df2 to df
    df = df.append(df2)
    

    results in:

                            Food  Clothes  Bills  Social  Travel  Art  Other  Daily_Total
    Week_End   Todays_Date                                                               
    2020-09-27 2020-09-21     25       25     25      25      25   25     25          175
               2020-09-23     20       20     20      20      20   20     20          140
               2020-09-24     12       12     12      12      12   12     12           84
               2020-09-25     20       20     20      20      20   20     20          140
               0              77       77     77      77      77   77     77          539