将 Pandas MultiIndex DataFrame 从按行转换为按列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15751283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a pandas MultiIndex DataFrame from rows-wise to column-wise
提问by Jason Strimpel
I'm working in zipline and pandas and have converted a pandas.Panelto a pandas.DataFrameusing the to_frame()method. This is the resulting pandas.DataFramewhich as you can see is multi-indexed:
我在 zipline 和 pandas 中工作,并已使用该方法pandas.Panel将 a转换为 a 。这就是由此而来正如你可以看到的是多索引:pandas.DataFrameto_frame()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
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.
我已经尝试过pivot 方法、stack/unstack 等,但这些方法不是我想要的。我真的很困在这一点上,任何帮助表示赞赏。
回答by bdiamante
Because you have a MultiIndex in place already, stackand unstackare what you want to use to move rows to cols and vice versa. That being said, unstackshould do exactly what you want to accomplish. If you have a DataFrame dfthen df2 = df.unstack('minor')should do the trick. Or more simply, since by default stack/unstackuse the innermost level, df2 = df.unstack().
因为您已经有了一个 MultiIndex,stack并且unstack您想用它来将行移动到列,反之亦然。话虽如此,unstack应该做你想要完成的事情。如果你有一个 DataFramedf那么df2 = df.unstack('minor')应该可以解决问题。或者更简单地说,因为默认情况下stack/unstack使用最内层,df2 = df.unstack().

