问题描述
我正在使用滑索和熊猫工作,并已使用to_frame()
方法将pandas.Panel
转换为pandas.DataFrame
.这就是生成的pandas.DataFrame
,如您所见,它是多索引的:
I'm working in zipline and pandas and have converted a pandas.Panel
to a pandas.DataFrame
using the to_frame()
method. This is the resulting pandas.DataFrame
which as you can see is multi-indexed:
price
major minor
2008-01-03 00:00:00+00:00 SPY 129.93
KO 26.38
PEP 64.78
2008-01-04 00:00:00+00:00 SPY 126.74
KO 26.43
PEP 64.59
2008-01-07 00:00:00+00:00 SPY 126.63
KO 27.05
PEP 66.10
2008-01-08 00:00:00+00:00 SPY 124.59
KO 27.16
PEP 66.63
我需要将此框架转换为如下形式:
I need to convert this frame to look like this:
SPY KO PEP
2008-01-03 00:00:00+00:00 129.93 26.38 64.78
2008-01-04 00:00:00+00:00 126.74 26.43 64.59
2008-01-07 00:00:00+00:00 126.63 27.05 66.10
2008-01-08 00:00:00+00:00 124.59 27.16 66.63
我尝试了数据透视方法,堆栈/非堆栈等方法,但是这些方法不是我想要的.在这一点上,我真的很坚持,不胜感激.
I've tried the pivot method, stack/unstack, etc. but these methods are not what I'm looking for. I'm really quite stuck at this point and any help is appreciated.
推荐答案
由于已经有了MultiIndex,因此您要使用stack
和unstack
将行移动到cols,反之亦然.话虽这么说,unstack
应该完全完成您想要完成的任务.如果您有DataFrame df
,则df2 = df.unstack('minor')
应该可以解决问题.或更简单地说,由于默认情况下stack
/unstack
使用最里面的级别df2 = df.unstack()
.
Because you have a MultiIndex in place already, stack
and unstack
are what you want to use to move rows to cols and vice versa. That being said, unstack
should do exactly what you want to accomplish. If you have a DataFrame df
then df2 = df.unstack('minor')
should do the trick. Or more simply, since by default stack
/unstack
use the innermost level, df2 = df.unstack()
.
这篇关于将Pandas MultiIndex DataFrame从行方式转换为列方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!