Title: Pivot Tables In Pandas
Slug: pandas_pivot_tables
Summary: Pivot Tables In Pandas
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon
In [15]:
import pandas as pd
In [16]:
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'],
'TestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'TestScore'])
df
Out[16]:
In [17]:
pd.pivot_table(df, index=['regiment','company'], aggfunc='mean')
Out[17]:
In [18]:
df.pivot_table(index=['regiment','company'], aggfunc='count')
Out[18]: