Articles → Pandas → Multilevel Index In Dataframe In Pandas

Multilevel Index In Dataframe In Pandas


import numpy as np
import pandas as pd

# Index Levels
outside = ['G1','G1','G1','G2','G2','G2']
inside = [1,2,3,1,2,3]
hier_index = list(zip(outside,inside))
hier_index = pd.MultiIndex.from_tuples(hier_index)

df = pd.DataFrame(np.random.randn(6,2),index=hier_index,columns=['A','B'])

# print the whole dataframe
print("Dataframe\n", df)

# Index at level 1
print("\nDataframe level 1 index\n", df.loc['G1'])

# Index at level 2
print("\nDataframe level 2 index\n", df.loc['G1'].loc[1])

# Element at column B
print("\nDataframe Element at column B\n", df.loc['G1'].loc[1]['B'])


Picture showing the output of the Multilevel index in dataframe in pandas
Click to Enlarge

Posted By  -  Karan Gupta
Posted On  -  Thursday, April 25, 2019


Your Email Id  
Query/FeedbackCharacters remaining 250