python - 使用第二个索引作为列将 Pandas 多索引系列转换为数据框

标签 python pandas numpy scipy

您好,我有一个具有 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/

相关文章:

python - 在 DataFrame 上创建列,比较两个系列之间的任何匹配

python - 为 scipy.optimize.curve_fit 函数中的各个独立点分配边界

python - 使用图片时出现ValueError == None

python - 在服务器上安全地执行不受信任的Python代码

python - PyCharm 没有在 "pass"上击中 Quick and Dirty 断点

python - 如何访问触发跟踪回调的特定 tkinter StringVar?

python - 按行格式化 Pandas 数据框

python - 如何将 2 个列表的列表转换为 pandas 中的 2 列 df

python - 快速计算条件函数的方法

python - 为 Elasticsearch 日志添加钩子(Hook)