使用以下DataFrame,我如何转移" beyer"基于索引而没有Pandas的列将移位值分配给不同的索引值?
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
问题在于Paynter被授予了最后枪手(他的第一张唱片)的指定。相反,我希望它像这样......
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
答案 0 :(得分:38)
使用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's
level
参数,从而将其分组到多个级别。