堆叠和整形DataFrame(pandas)切片而不循环(Stacking and shaping slices of DataFrame (pandas) without looping)
我有一个以下形式的DataFrame:
var1 var2 var3 day 0 -0.001284819 0.00138089 1.022781 1 1 -0.001310201 0.001377473 1.022626 1 2 -0.001330947 0.001374873 1.022477 2 3 -0.0013596 0.001430423 1.022385 2 4 -0.001361913 0.00144389 1.02228 3 5 -0.001371761 0.001440607 1.022161 3 6 -0.001393955 0.00143729 1.022017 4 7 -0.001431099 0.00143434 1.021908 4 8 -0.001466792 0.00143334 1.021749 5 9 -0.001491 0.00143159 1.021602 5
每个变量var1到var3是一个时间序列,每天记录两个样本。 我正在尝试将此DataFrame转换为以下内容:
day 1 2 3 4 5 0 var1 -0.001284819 -0.001330947 -0.001361913 -0.001393955 -0.001466792 1 -0.001310201 -0.0013596 -0.001371761 -0.001431099 -0.001491 2 var2 0.00138089 0.001374873 0.00144389 0.00143729 0.00143334 3 0.001377473 0.001430423 0.001440607 0.00143434 0.00143159 4 var3 1.022781 1.022477 1.02228 1.022017 1.021749 5 1.022626 1.022385 1.022161 1.021908 1.021602
现在每列都是一天,并且在每一天内,每个变量仍然与原始时间序列中的顺序相同。
我一直试图找到一种方法来实现这种结果,使用这种旋转,堆叠和操作,以避免循环,但到目前为止,我无法管理。
关于如何解决这个问题的任何建议/提示/想法将非常感谢:)
I have a DataFrame of the following form:
var1 var2 var3 day 0 -0.001284819 0.00138089 1.022781 1 1 -0.001310201 0.001377473 1.022626 1 2 -0.001330947 0.001374873 1.022477 2 3 -0.0013596 0.001430423 1.022385 2 4 -0.001361913 0.00144389 1.02228 3 5 -0.001371761 0.001440607 1.022161 3 6 -0.001393955 0.00143729 1.022017 4 7 -0.001431099 0.00143434 1.021908 4 8 -0.001466792 0.00143334 1.021749 5 9 -0.001491 0.00143159 1.021602 5
Each variable var1 to var3 is a time series and two samples are recorded every day. I'm trying to transform this DataFrame into something like this:
day 1 2 3 4 5 0 var1 -0.001284819 -0.001330947 -0.001361913 -0.001393955 -0.001466792 1 -0.001310201 -0.0013596 -0.001371761 -0.001431099 -0.001491 2 var2 0.00138089 0.001374873 0.00144389 0.00143729 0.00143334 3 0.001377473 0.001430423 0.001440607 0.00143434 0.00143159 4 var3 1.022781 1.022477 1.02228 1.022017 1.021749 5 1.022626 1.022385 1.022161 1.021908 1.021602
Now each column is a day, and within each day, each variable is still in the same order as in the original time series.
I've been trying to figure out a way of achieving this result using pivoting, stacking and operations of this sort to avoid looping but so far I haven't be able to manage.
Any suggestions/hints/ideas on how to solve this would be very much appreciated :)
原文:https://stackoverflow.com/questions/22719649