如何在 Pandas DataFrames 中切片多索引列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12590131/
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
How to slice multindex columns in pandas DataFrames?
提问by Phillip Cloud
I have a DataFrameobject with 16 rows and 14671872 columns. I cannot for the life of me figure out how to slice this array in any reasonable amount of time on a quad core Dell T410 with 24GB of RAM.
我有一个DataFrame16 行和 14671872 列的对象。我终其一生都无法弄清楚如何在具有 24GB RAM 的四核 Dell T410 上以任何合理的时间分割此阵列。
I would just use the transpose of the array because that's muchfaster, but then I would have a MultiIndexon the columns, and I haven't yet found any documentation in Pandas showing how to use MultiIndexs as columns.
我只会使用数组的转置,因为这样会快得多,但是我会MultiIndex在列上有一个,而且我还没有在 Pandas 中找到任何文档来展示如何使用MultiIndexs 作为列。
I thought about opening up an issue on the Github tracker, but I wanted to post here before I did that just in case I missed something totally obvious.
我想在 Github 跟踪器上打开一个问题,但我想在我这样做之前先在这里发帖,以防我错过了一些非常明显的东西。
回答by jmloser
I think .xs might do what you want.
我认为 .xs 可能会做你想做的。
To get all shank 1's (i.e. where the first level of the MultiIndex is equal to 1).
获取所有小腿 1(即 MultiIndex 的第一级等于 1)。
df.xs(1, axis=1, level=0)
This is pretty flexible if you need to cross-section by a different level of the MultiIndex as well.
如果您还需要通过不同级别的 MultiIndex 进行横截面,这非常灵活。

