<jupyter_start><jupyter_text>---title: "Hierarchical Data In pandas"author: "<NAME>"date: 2017-12-20T11:53:49-07:00description: "Hierarchical Data In pandas."type: technical_notedraft: false---<jupyter_code># import modules
import pandas as pd
# Create dataframe
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 
        'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 
        'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 
        'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])
df
# Set the hierarchical index but leave the columns inplace
df = df.set_index(['regiment', 'company'], drop=False)
df
# Set the hierarchical index to be by regiment, and then by company
df = df.set_index(['regiment', 'company'])
df
# View the index
df.index
# Swap the levels in the index
df.swaplevel('regiment', 'company')
# Summarize the results by regiment
df.sum(level='regiment')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19939804364183597, 'fraction_numerical': 0.0526711813393529, 'mean_word_length': 5.487804878048781, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '423685', 'license': 'CC0-1.0', 'n_tokens_mistral': 556, 'n_tokens_neox': 486, 'n_words': 143, 'path': 'docs/python/data_wrangling/pandas_hierarchical_data.ipynb', 'repo_name': 'revgizmo-forks/ds_notes', 'size': '1334'}