python - 多索引行和列
问题描述
如何在 python 中对行和列进行多索引?
解决方案
import pandas as pd # Pandas isn't mentioned in the tags, but the image looks like a pandas dataframe.
idx = pd.MultiIndex.from_product([[f'System {s}' for s in 'ABC'], list('FM')], names=[None, 'Sex'])
cols = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2), ('B', 3), ('C', 1), ('C', 2)])
df = pd.DataFrame(data=1, columns=cols, index=idx)
>>> df
A B C
1 2 1 2 3 1 2
Sex
System A F 1 1 1 1 1 1 1
M 1 1 1 1 1 1 1
System B F 1 1 1 1 1 1 1
M 1 1 1 1 1 1 1
System C F 1 1 1 1 1 1 1
M 1 1 1 1 1 1 1
>>> df.loc[:, 'B']
1 2 3
Sex
System A F 1 1 1
M 1 1 1
System B F 1 1 1
M 1 1 1
System C F 1 1 1
M 1 1 1
或使用 IndexSlice。
>>> df.loc[:, pd.IndexSlice['B', :]]
B
1 2 3
Sex
System A F 1 1 1
M 1 1 1
System B F 1 1 1
M 1 1 1
System C F 1 1 1
M 1 1 1
推荐阅读
- angular - 如何修复重定向调用的错误:“无法读取未定义类型错误的属性‘拆分’”
- c# - OAuthPrompt Waterfall 需要启动两次才能让 RouteAsync 被多次调用
- .net-core - 如何使用子域将客户端 ID 委托给 Azure B2C 进行身份验证
- c - 为什么我的代码没有在这个链表中插入一个新节点?
- jsf - HttpServletRequest.getParameter 打破 Primefaces FileUploadFilter?
- java - ImageView 折叠并且不显示创建的缩略图
- elixir - if 块中定义的函数是否在编译时被取出?如果在编译时运行,顶层会运行吗?
- javascript - 使用 Apollo 和 GraphQL 的 React 表单不会触发 onSubmit
- c# - 将 FieldNames 和 Values 动态传递给 linq
- php - 在每个数组项上添加键/值 - PHP