首页 > 解决方案 > 多索引行和列

问题描述

如何在 python 中对行和列进行多索引?

在此处输入图像描述

标签: pythonpivot-tabledata-sciencecrosstab

解决方案


https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-indexing-with-hierarchical-index

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

推荐阅读