pandas 使用多级列设置索引
Posted
技术标签:
【中文标题】pandas 使用多级列设置索引【英文标题】:pandas set index with multilevel columns 【发布时间】:2019-11-09 08:04:31 【问题描述】:考虑以下pd.DataFrame
df_index = pd.MultiIndex.from_product([['foo','bar'],['one','two','three']])
df = pd.DataFrame(np.random.randint(0,10,size=18, dtype='int').reshape((-1,6)), columns=df_index)
print(df)
foo bar
one two three one two three
0 7 3 8 3 6 0
1 2 5 9 4 3 6
2 4 2 6 6 4 5
我希望将'foo'
和其中的所有子索引设置为索引。我怎样才能做到这一点?我正在努力解决'set_index'
和pd.IndexSlice
,但仍然无法找到解决方案
【问题讨论】:
【参考方案1】:您需要将MultiIndex
的所有级别作为元组传递。所以正确的格式应该是:
df.set_index([('foo', 'one'), ('foo', 'two'), ('foo', 'three')])
如果这很麻烦,您可以使用以下列表理解创建索引:
idx = [x for x in df.columns if x[0] == 'foo']
print(idx)
# [('foo', 'one'), ('foo', 'two'), ('foo', 'three')]
df.set_index(idx)
[出]
bar
one two three
(foo, one) (foo, two) (foo, three)
1 3 4 4 8 3
5 1 0 4 7 5
0 0 3 9 1 6
【讨论】:
我试过 df.set_index(('foo','one','two','three')) 和 df.set_index(('foo',('one','two' ,'three')))..那个偏题没用。以上是关于pandas 使用多级列设置索引的主要内容,如果未能解决你的问题,请参考以下文章