Unstacking in Python

This post is a follow up from a previous post. The Python solution is presented here.

Tip: Pandas MultiIndex.

Question #1: Dataset.

Code:

# -*- coding: utf-8 -*-
“””
Created on Wed Dec 02 12:11:14 2015

@author: agoswami
“””

import pandas as pd

df = pd.read_csv(r’E:\datasets\12Dec\ReshapingData1_Q1.txt’, sep = ‘\t’)

byidyear = df.groupby([‘ID’, ‘Year’])
reshaped = byidyear[‘Value’].mean().unstack()

reshaped.to_csv(r’E:\datasets\12Dec\ReshapedData1_Q1_Python.txt’, sep=’\t’)

 

Question #2:  Dataset.

Code:

# -*- coding: utf-8 -*-
“””
Created on Wed Dec 02 12:35:47 2015

@author: agoswami
“””

import pandas as pd

df = pd.read_csv(r’E:\datasets\12Dec\ReshapingData1_Q2.txt’, sep = ‘\t’)

bydatelanguageapp = df.groupby([‘Date’, ‘LanguageTag’, ‘App’])
df_groupedmean = bydatelanguageapp[‘AcceptanceRate’].mean()

#Unstack the ‘App’ column
reshaped = df_groupedmean.unstack()

reshaped.to_csv(r’E:\datasets\12Dec\ReshapedData1_Q2_Python.txt’, sep=’\t’)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s