首页 > 解决方案 > 在 pandas 数据框中使用 str.extract 创建多索引

问题描述

我有一个数据框,其中的列和行的名称如下索引:

idx = ['CAN_agr', 'CAN_ser', 'USA_agr', 'USA_ser', 'MEX_agr', 'MEX_ser']
sample = pd.DataFrame(
[[1, 2, 3, 4, 5 ,6],
[7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36]],
index = idx,
columns=idx
)

我想使用这些名称来创建多索引,其中 level=0 将是国家/地区的名称(即 CAN、USA、MEX),而 level=1 将具有每个国家/地区的行业类型(即 agr、ser)。我想过使用 str.extract,但我不确定如何根据国家和行业类型分离标签并将它们分配为多索引列和行。谁能帮助我应该如何解决这个问题?非常感谢!

标签: pythonpandasdataframemulti-index

解决方案


split索引和列_,然后将它们分配回索引和列应该执行的操作:

sample.index = sample.index.str.split('_', expand=True)
sample.columns = sample.columns.str.split('_', expand=True)
sample

        CAN     USA     MEX    
        agr ser agr ser agr ser
CAN agr   1   2   3   4   5   6
    ser   7   8   9  10  11  12
USA agr  13  14  15  16  17  18
    ser  19  20  21  22  23  24
MEX agr  25  26  27  28  29  30
    ser  31  32  33  34  35  36

推荐阅读