熊猫用多级列设置索引

Sir*_* S. 5 python numpy multi-index pandas

考虑以下 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
Run Code Online (Sandbox Code Playgroud)

我希望将'foo'其中的所有子索引都设置为索引。我该如何实现?我拼杀'set_index'pd.IndexSlice,但仍不能得到解决

Chr*_*s A 2

您需要将 a 的所有级别MultiIndex作为元组传递。所以正确的格式应该是:

df.set_index([('foo', 'one'), ('foo', 'two'), ('foo', 'three')])
Run Code Online (Sandbox Code Playgroud)

如果这很麻烦,您可以使用列表理解来创建索引,例如:

idx = [x for x in df.columns if x[0] == 'foo']
print(idx)
#  [('foo', 'one'), ('foo', 'two'), ('foo', 'three')]

df.set_index(idx)
Run Code Online (Sandbox Code Playgroud)

[出去]

                                   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
Run Code Online (Sandbox Code Playgroud)