如何在python中对行和列进行多重索引?
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9hdnB3MC5wbmcifQ==” alt =“在此处输入图像描述”>
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