使用下面的数据帧,如何在不让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
使用
groupby/shift
将移位单独应用于每个组:(感谢Jeff指出了这种简化。)如果有多索引,则可以通过向
groupby's
level
参数传递一个ints
序列或级别名称来按多个级别分组。相关问题 更多 >
编程相关推荐