Jungletronics
Published in

Jungletronics

Pandas — Hierarchical Index & Cross-section

Open your Colab notebook and here are the follow-up exercises! — #PySeries#Episode 10

print(‘Hello, Advanced Pandas: Hierarchical Index & Cross-section!’)
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)

Pandas — MultiIndex & Advanced Index

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(randn(6,2), hier_index, [‘A’, ‘B’])df

Calling Data:

# If we want everything that is under ‘G1’, type df.loc():
# We will get a sub-set ‘G1’ of the DataFrame; check it out:
df.loc[‘G1’]
df.loc[‘G1’].loc[1]
df.loc['G1'].loc[1][0]
2.706849839399938

Naming Columns:

# Indexes do not have any namesdf.index.namesFrozenList([None, None])
df.index.names = [‘Groups’, ‘Nums’]
# Now when we call it we have the outside label
# as ‘Groups’ and inside ‘Nums’
df

Location and grabbing — Cross-Section:

df.loc[‘G2’].loc[2][‘B’]
##Cross Section — Multi Level Index
# Let’s say we want to grab everything under ‘Nums’ = 1
# with both groups;
# What differentiates it from the loc method is that
# we can skip or go inside the multi-level index
# This is to say: grab a cross-section where the
# level is equal 1 and level is equal ‘Nums’
df.xs(1, level=’Nums’)
print(“Thank you for Reading this Post! See you in the next PySeries Episode o/”)

Posts Related:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
J3

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!