# ---
# title: "Crosstabs In pandas"
# author: "<NAME>"
# date: 2017-12-20T11:53:49-07:00
# description: "Crosstabs In pandas."
# type: technical_note
# draft: false
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ### Import pandas

import pandas as pd

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 
        'company': ['infantry', 'infantry', 'cavalry', 'cavalry', 'infantry', 'infantry', 'cavalry', 'cavalry','infantry', 'infantry', 'cavalry', 'cavalry'], 
        'experience': ['veteran', 'rookie', 'veteran', 'rookie', 'veteran', 'rookie', 'veteran', 'rookie','veteran', 'rookie', 'veteran', 'rookie'],
        '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', 'experience', 'name', 'preTestScore', 'postTestScore'])
df

df.apply(pd.value_counts)
# df.select_dtypes(include=['object']).apply(lambda df:pd.Series(df.apply(pd.unique)))

# ### Create a crosstab table by company and regiment
#
# Counting the number of observations by regiment and category

pd.crosstab(df.regiment, df.company, margins=True)

# ### Create a crosstab of the number of rookie and veteran cavalry and infantry soldiers per regiment

pd.crosstab([df.company, df.experience], df.regiment,  margins=True)

StarcoderdataJupyterScriptsDedupFiltered