pandas 设置多级列索引

问题描述 投票:0回答:2

考虑以下内容

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
但仍然无法找到解决方案

python pandas numpy multi-index
2个回答
2
投票

您需要将

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

0
投票

怎么样

df.index = pd.MultiIndex.from_arrays(df.foo.values.T, names=df.foo.columns)
© www.soinside.com 2019 - 2024. All rights reserved.