python - 在 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,但我不确定如何根据国家和行业类型分离标签并将它们分配为多索引列和行。谁能帮助我应该如何解决这个问题?非常感谢!
解决方案
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
推荐阅读
- mysql - sequelize 中的嵌套查询
- jquery - 无法禁用下拉列表中的某些特定选项
- javascript - React Native 无法访问 api
- android - 当用户启动一些选定的应用程序时启动我的活动
- sql - 如何获取第一个表的每个 ID 的电子邮件 ID(一个值),然后在 SQL Server 2012 中将第二个表中的电子邮件名称显示为逗号分隔?
- selenium-webdriver - 从命令行运行 webdriver.io 以在 microsoft vsts build 上运行测试
- python - 十六进制颜色列表适用于饼图但不适用于绘图
- javascript - 在反应进度条中,如何使地图标记跟随填充的百分比?
- laravel - 当模型在参数的类型提示中时,Laravel 5.6 找不到页面
- python - python单元测试testsuite不调用任何测试用例