python - 如何从 Pandas 数据框中的多索引创建列?

标签 python pandas dataframe multi-index

我有以下 df:

import numpy as np
import pandas as pd
from pandas import *


arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
      np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]


s = pd.Series(np.random.randn(8), index=arrays)

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

这看起来像:

                0         1         2         3
bar one -0.986089 -0.501170  1.635501 -0.789489
    two  1.890491 -0.022640 -1.649097  0.984925
baz one -0.759930 -1.640487 -0.763909 -0.554997
    two  1.636005  0.037158  0.567383  0.770314
foo one  0.709847  0.048332 -0.676660  1.059454
    two  0.588063  0.568405  1.619102  0.393631
qux one -0.735497 -0.589282  1.015266  0.934877
    two -0.380719  0.822213  0.295152 -0.838549

我想获得的是两个有两列表示索引:

                0         1         2         3 col1 col2
bar one -0.986089 -0.501170  1.635501 -0.789489  bar  one
    two  1.890491 -0.022640 -1.649097  0.984925  bar  two
baz one -0.759930 -1.640487 -0.763909 -0.554997  baz  one
    two  1.636005  0.037158  0.567383  0.770314  baz  two
foo one  0.709847  0.048332 -0.676660  1.059454  foo  one
    two  0.588063  0.568405  1.619102  0.393631  foo  two
qux one -0.735497 -0.589282  1.015266  0.934877  qux  one
    two -0.380719  0.822213  0.295152 -0.838549  qux  two

如果我只有一级索引,通常的代码是:

df['col'] = df.index

如何在多级索引上执行此操作?

最佳答案

如果你只是想把不同的级别推到列中,你可以像这样重置索引:

df = df.reset_index()

要获得显示的内容,您可以使用 get_level_values 访问每个级别的值,如下所示:

In [69]: df['col1'] = df.index.get_level_values(0)

In [70]: df['col2'] = df.index.get_level_values(1)

In [71]: df
Out[71]: 
                0         1         2         3 col1 col2
bar one  0.523779  0.391620  0.726137  0.025270  bar  one
    two  0.569344  2.199075 -1.280942 -0.703693  bar  two
baz one  0.347541 -0.423759 -1.010009 -0.349585  baz  one
    two -0.894432 -0.335773 -0.550428  0.217038  baz  two
foo one  0.688120 -1.123873  0.784451  0.482187  foo  one
    two  0.062910 -0.705614  0.205807 -0.723899  foo  two
qux one -0.304601  0.130234  0.303403  1.348833  qux  one
    two -0.931551  0.655013  0.622796 -0.738110  qux  two

关于python - 如何从 Pandas 数据框中的多索引创建列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32275910/

相关文章:

python NumPy : Change the column type of a numpy matrix

python - Pandas 设置单级索引名称

python - 如何在 Pandas 中绘制 groupby 之后的聚合结果?

r - 根据前n行有条件地创建一个新列

从列表提取中删除级别到数据帧

python - auth.User.groups : (fields. E304) 'User.groups' 的反向访问器与 'UserManage.groups' 的反向访问器冲突

python - 使用 numba 加快拍摄速度?

python - 替换数据框中的列值的正确方法是什么?

python - 字典控制 turtle 的运动

python - 将按行排序的数据帧映射到原始列标签(Pandas),但仅限那些值大于零的标签