Vic
Vic

Reputation: 1

Multi-indexed row and columns

How can I do multi index of rows and columns in python?

enter image description here

Upvotes: 0

Views: 53

Answers (1)

Alexander
Alexander

Reputation: 109666

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.

>>> 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

Upvotes: 1

Related Questions