您好,我有一个具有 2 级多索引和一列的 DataFrame/Series。我想将二级索引用作列。例如(代码取自 multi-index docs ):
import pandas as pd
import numpy as np
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'])
s = pd.DataFrame(np.random.randn(8), index=index, columns=["col"])
看起来像:
first second
bar one -0.982656
two -0.078237
baz one -0.345640
two -0.160661
foo one -0.605568
two -0.140384
qux one 1.434702
two -1.065408
dtype: float64
我想要的是具有索引 [bar, baz, foo, qux]
和列 [one, two]
的 DataFrame。
最佳答案
你只需要unstack
你的系列:
>>> s.unstack(level=1)
second one two
first
bar -0.713374 0.556993
baz 0.523611 0.328348
foo 0.338351 -0.571854
qux 0.036694 -0.161852
关于python - 使用第二个索引作为列将 Pandas 多索引系列转换为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44142591/