如何使用多索引转移Pandas数据帧?

2024-05-08 15:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

使用下面的数据帧,如何在不让Pandas将移位值分配给其他索引值的情况下,基于索引移位“beyer”列?

                  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

Tags: 数据pandasdfdateline情况nanlast
1条回答
网友
1楼 · 发布于 2024-05-08 15:36:44

使用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

如果有多索引,则可以通过向groupby'slevel参数传递一个ints序列或级别名称来按多个级别分组。

相关问题 更多 >