[英]Shifting rows with multiindex Pandas
I want to create a table of stocks consisting of three columns: 我想创建一个由三列组成的库存表:
Quantity Day - 1 | 数量-1 | Quantity traded |
交易数量 Quantity Day 0
数量天0
The stocks come in a frame like : 股票的框架如下:
> df
Date Stock Quantity
2019-04-01 ALSC3 19600
AMAR3 3080
2019-04-02 ALSC3 4000
AMAR3 3070
I expected that a simple shift would match the index (Date,StockTicker), but in reality it ignores the index and shifts the row entirely. 我希望可以通过简单的移位来匹配索引(Date,StockTicker),但实际上,它会忽略索引并完全移位行。
Date Stock Quantity Day-1
2019-04-01 ALSC3 3080
AMAR3 4000
2019-04-02 ALSC3 3070
AMAR3 NaN
Does anyone know how to perform it correctly? 有人知道如何正确执行吗? I would like something like this:
我想要这样的东西:
Date Stock Quantity Quantity Day -1
2019-04-01 ALSC3 19600 4000
AMAR3 3080 3070
2019-04-02 ALSC3 4000 NaN
AMAR3 3070 NaN
Here you go, assuming the date index are countinuous. 假设日期索引是不连续的,那么您就来了。
df.Quantity.groupby(level=1).shift(-1)
This matches your expected output. 这符合您的预期输出。 Although I think "Quantity Day-1" means
shift()
instead of shift(-1)
. 尽管我认为“第1天数量”表示
shift()
而不是shift(-1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.