Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.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 pandas Multiindex columns方法选择返回所有列而不是子集_Python_Pandas_Multi Index - Fatal编程技术网

Python pandas Multiindex columns方法选择返回所有列而不是子集

Python pandas Multiindex columns方法选择返回所有列而不是子集,python,pandas,multi-index,Python,Pandas,Multi Index,嗨,这是一个我不理解的行为例子。 下面是一个列中多索引的示例 arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first

嗨,这是一个我不理解的行为例子。 下面是一个列中多索引的示例

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])

df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index)
现在,我想按第一级选择df的子集,并返回相关列:

df.loc[:, ['bar']].columns
返回

MultiIndex(levels=[['bar'], ['one', 'two']],
           labels=[[0, 0], [0, 1]],
           names=['first', 'second'])
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=['first', 'second'])
但是

返回

MultiIndex(levels=[['bar'], ['one', 'two']],
           labels=[[0, 0], [0, 1]],
           names=['first', 'second'])
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=['first', 'second'])
第二个将返回所有列名而不是

MultiIndex(levels=[['bar', 'baz'], ['one', 'two']] etc...
更重要的是,是否有任何快速修复方法,以便我只能返回相关数据

这一点变得更加重要,因为熊猫是不推荐的面板(这曾经是存储多维数据的一种非常优雅的方式)

在新的熊猫版本(
0.20.1
)中,使用:


.

非常感谢。在我看来,这是一种非常奇怪的行为,因为它对一个或多个对象的行为并不相同。