Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多索引数据帧从行转换为列_Python_Pandas_Multi Index_Zipline - Fatal编程技术网

Python 将多索引数据帧从行转换为列

Python 将多索引数据帧从行转换为列,python,pandas,multi-index,zipline,Python,Pandas,Multi Index,Zipline,我在zipline和pandas中工作,使用to_frame()方法将pandas.Panel转换为pandas.DataFrame。这是结果pandas.DataFrame,如您所见,它是多索引的: price major minor 2008-01-03 00:00:00+00:00 SPY 129.93

我在zipline和pandas中工作,使用
to_frame()
方法将
pandas.Panel
转换为
pandas.DataFrame
。这是结果
pandas.DataFrame
,如您所见,它是多索引的:

                                  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
我需要将此帧转换为如下所示:

                          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

我尝试过pivot方法、stack/unstack等,但这些方法不是我想要的。在这一点上我真的很困惑,非常感谢您的帮助。

因为您已经有了一个多索引,
堆栈和
取消堆栈
是您想要用来将行移动到列,反之亦然。也就是说,
unstack
应该完全完成您想要完成的任务。如果您有一个数据帧
df
,那么
df2=df.unstack('minor')
应该可以做到这一点。或者更简单地说,由于默认情况下
stack
/
unstack
使用最内层,
df2=df.unstack()

Aargh;比我快<代码>pivot
应该也能工作,在重置索引后,即
df.reset_index().pivot(“主”、“次”)
(带或不带
,“价格”)
[“价格”]
,这取决于名称是否仍在浮动)哈,很好,我显然没有正确使用unstack,谢谢。