pandas 多索引列方法选择 returns 所有列而不是子集
pandas Multiindex columns method selection returns all columns instead of subset
您好,这是一个我不理解的行为示例。
这是列中多索引的示例
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)
现在我想 select 第一级的 df 子集和 return 相关列:
df.loc[:, ['bar']].columns
returns
MultiIndex(levels=[['bar'], ['one', 'two']],
labels=[[0, 0], [0, 1]],
names=['first', 'second'])
但是
df.loc[:, ['bar', 'baz']].columns
returns
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['first', 'second'])
为什么第二个会 return 所有列名而不是
MultiIndex(levels=[['bar', 'baz'], ['one', 'two']] etc...
更重要的是,有什么快速修复方法可以让我 return 只有相关数据吗?
这变得更加相关,因为 pandas 正在弃用面板(它曾经是存储多维数据的一种非常优雅的方式)
在新的 pandas 版本 (0.20.1
) 中使用 MultiIndex.remove_unused_levels
:
print (df.loc[:, ['bar', 'baz']].columns)
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['first', 'second'])
print (df.loc[:, ['bar', 'baz']].columns.remove_unused_levels())
MultiIndex(levels=[['bar', 'baz'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['first', 'second'])
您好,这是一个我不理解的行为示例。 这是列中多索引的示例
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)
现在我想 select 第一级的 df 子集和 return 相关列:
df.loc[:, ['bar']].columns
returns
MultiIndex(levels=[['bar'], ['one', 'two']],
labels=[[0, 0], [0, 1]],
names=['first', 'second'])
但是
df.loc[:, ['bar', 'baz']].columns
returns
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['first', 'second'])
为什么第二个会 return 所有列名而不是
MultiIndex(levels=[['bar', 'baz'], ['one', 'two']] etc...
更重要的是,有什么快速修复方法可以让我 return 只有相关数据吗?
这变得更加相关,因为 pandas 正在弃用面板(它曾经是存储多维数据的一种非常优雅的方式)
在新的 pandas 版本 (0.20.1
) 中使用 MultiIndex.remove_unused_levels
:
print (df.loc[:, ['bar', 'baz']].columns)
MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['first', 'second'])
print (df.loc[:, ['bar', 'baz']].columns.remove_unused_levels())
MultiIndex(levels=[['bar', 'baz'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
names=['first', 'second'])