2014-04-21 46 views
16

使用以下DataFrame,如何在不將Pandas分配給不同索引值的情況下,根據索引移動「beyer」列?你如何將Pandas DataFrame換成多重索引?

    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)產生...

    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 

的問題是,潘德給出的最後一條槍手(他的第一個記錄)被分配了拜爾。相反,我希望它是這樣的......

    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 

回答

25

使用groupby/shift申請單獨轉移到各組:(感謝Jeff指出了該簡化)

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 

如果你有一個多指標,您可以通過將ints或等級名稱的序列傳遞給groupby'slevel參數將多個等級分組。

+0

這工作完美。謝謝! – TravisVOX

+0

我想我們應該把它添加到食譜。你有機會可以做一個公關嗎? – Jeff

+0

它爲什麼會引起這個... ValueError:不能從重複軸重新索引 – TravisVOX

相關問題