简体   繁体   English

多索引行和列

[英]Multi-indexed row and columns

How can I do multi index of rows and columns in python?如何在 python 中对行和列进行多索引?

在此处输入图像描述

https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-indexing-with-hierarchical-index 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

Or using IndexSlice.或使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM