2015-07-30 8 views
6

Können Sie bitte helfen, zwei multiindexed pandas Datenrahmen anzuhängen? Es wird versucht, df_future an df_current anzuhängen. COMPANY und DATE sind die Indizes.Append zwei multiindexed pandas dateframes

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 

Basierend auf diesen dfs, wollen sehen ..

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 

Antwort

6

Verwenden concat concate nate die beiden Datenrahmen und sort_index den ersten Indexebene neu zu ordnen:

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 

Hinweis: Meine ursprüngliche Antwort sortlevel verwendet, die jetzt veraltet. Verwenden Sie als firelynx shows stattdessen sort_index.

+0

Herr unutbu, Sie sind tolle! Ich danke dir sehr! –

3

Anhängen in Pandas heißt concat. Und geschieht mit the pd.concat function.

Die concat Funktion funktioniert unabhängig davon, ob Sie haben Multiindex oder nicht

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 

Und wenn die Sortierung ein Problem ist, verwenden Sie einfach:

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 
+0

Wusste nicht über df.sort_index() Teil. Vielen Dank! –