Add two multi-indexed pandas dataframes

Can you help add two multi-indexed pandas dataframes? Trying to add df_future to df_current. COMPANY and DATE are indices.

df_current

VALUE COMPANY DATE 7/27/2015 1 A 7/28/2015 2 7/29/2015 3 7/30/2015 4 7/27/2015 11 B 7/28/2015 12 7/29/2015 13 7/30/2015 14 

df_future

  VALUE COMPANY DATE A 8/1/2015 5 8/2/2015 6 B 8/1/2015 15 8/2/2015 16 

Based on these dfs you want to see ..

df_current_and_future

  VALUE COMPANY DATE 7/27/2015 1 7/28/2015 2 A 7/29/2015 3 7/30/2015 4 8/1/2015 5 8/2/2015 6 7/27/2015 11 7/28/2015 12 B 7/29/2015 13 7/30/2015 14 8/1/2015 15 8/2/2015 16 
+6
source share
2 answers

Use concat to combine the two DataFrames and sort_index to reorder the first level of the index:

 In [167]: pd.concat([df_current, df_future]).sort_index() Out[167]: VALUE COMPANY DATE A 7/27/2015 1 7/27/2015 11 7/28/2015 2 7/29/2015 3 7/30/2015 4 8/1/2015 5 8/2/2015 6 B 7/28/2015 12 7/29/2015 13 7/30/2015 14 8/1/2015 15 8/2/2015 16 

Note. My original answer uses sortlevel , which is now deprecated. As shown by firelynx , use sort_index .

+6
source

Adding to pandas is called concat. And executed with the pd.concat function.

The concat function works whether you have a multi-index or not

 df = pd.concat([df_current, future]) VALUE COMPANY DATE A 7/27/2015 1 7/28/2015 2 7/29/2015 3 7/30/2015 4 7/27/2015 11 B 7/28/2015 12 7/29/2015 13 7/30/2015 14 A 8/1/2015 5 8/2/2015 6 B 8/1/2015 15 8/2/2015 16 

And if sorting is a problem, just use:

 df.sort_index() VALUE COMPANY DATE A 7/27/2015 1 7/27/2015 11 7/28/2015 2 7/29/2015 3 7/30/2015 4 8/1/2015 5 8/2/2015 6 B 7/28/2015 12 7/29/2015 13 7/30/2015 14 8/1/2015 15 8/2/2015 16 
+3
source

All Articles