2014-04-21 18 views
16

Con il seguente DataFrame, come posso spostare la colonna "beyer" in base all'indice senza che Pandas assegni il valore spostato a un altro valore di indice?Come si sposta Pandas DataFrame con un multiindex?

    line_date line_race beyer 
horse           
Last Gunfighter 2013-09-28   10  99 
Last Gunfighter 2013-08-18   10 102 
Last Gunfighter 2013-07-06   8 103 
..... 
Paynter   2013-09-28   10 103 
Paynter   2013-08-31   10  88 
Paynter   2013-07-27   8 100 

df['beyer'].shift(1) produce ...

    line_date line_race beyer beyer_shifted 
horse              
Last Gunfighter 2013-09-28   10  99   NaN 
Last Gunfighter 2013-08-18   10 102    99 
Last Gunfighter 2013-07-06   8 103   102 
..... 
Paynter   2013-09-28   10 103    71 
Paynter   2013-08-31   10  88   103 
Paynter   2013-07-27   8 100    88 

Il problema è che Paynter è stato dato un Beyer che Ultimo Gunfighter (il suo primo disco) è stato assegnato. Invece voglio che vada così ...

    line_date line_race beyer beyer_shifted 
horse              
Last Gunfighter 2013-09-28   10  99   NaN 
Last Gunfighter 2013-08-18   10 102    99 
Last Gunfighter 2013-07-06   8 103   102 
..... 
Paynter   2013-09-28   10 103   NaN 
Paynter   2013-08-31   10  88   103 
Paynter   2013-07-27   8 100    88 

risposta

25

Usa groupby/shift per applicare il passaggio a ciascun gruppo: (. Grazie a Jeff per sottolineare questa semplificazione)

In [60]: df['beyer_shifted'] = df.groupby(level=0)['beyer'].shift(1); df 
Out[61]: 
        line_date line_race beyer beyer_shifted 
Last Gunfighter 2013-09-28   10  99   NaN 
Last Gunfighter 2013-08-18   10 102    99 
Last Gunfighter 2013-07-06   8 103   102 
Paynter   2013-09-28   10 103   NaN 
Paynter   2013-08-31   10  88   103 
Paynter   2013-07-27   8 100    88 

Se si dispone di un multiindice, è possibile raggruppare per più di un livello passando una sequenza di ints o nomi di livello al parametro groupby'slevel.

+0

Questo ha funzionato perfettamente. Grazie! – TravisVOX

+0

Penso che dovremmo aggiungere questo al ricettario. puoi fare un PR quando hai una possibilità? – Jeff

+0

Perché restituire questo errore ValueError: impossibile reindicizzare da un asse duplicato – TravisVOX

Problemi correlati