# Python Pandas For Your Grandpa - 4.7 Challenge: Rose Thorn

Contents

## Setup

You developed a multi-player indie game called “Rose Thorn”. Players compete in one of two venues - the ocean or the desert. You track the outcome of five games between three players in a DataFrame called `games`, and now you want to analyze the data. Convert the `games` DataFrame into a new DataFrame that identifies how many times each (player, placement) occurs per venue, specifically with `venue` as the row index and `(player, placed)` as the column MultiIndex.

``````import numpy as np
import pandas as pd

games = pd.DataFrame({
'bella1':   ['2nd', '3rd', '1st', '2nd', '3rd'],
'billybob': ['1st', '2nd', '2nd', '1st', '2nd'],
'nosoup4u': ['3rd', '1st', '3rd', '3rd', '3rd'],
'venue': ['desert', 'ocean', 'desert', 'ocean', 'desert']
})
print(games)
##   bella1 billybob nosoup4u   venue
## 0    2nd      1st      3rd  desert
## 1    3rd      2nd      1st   ocean
## 2    1st      2nd      3rd  desert
## 3    2nd      1st      3rd   ocean
## 4    3rd      2nd      3rd  desert
``````

## Solution

``````step1 = games.melt(id_vars='venue', var_name='player', value_name='placed')
step1['venue'] = pd.Categorical(step1.venue)
step1['player'] = pd.Categorical(step1.player)
step1['placed'] = pd.Categorical(step1.placed)
step2 = step1.groupby(['venue', 'player', 'placed']).agg('size')
step3 = step2.unstack(level=['player','placed'])
print(step3)
## player bella1         billybob         nosoup4u
## placed    1st 2nd 3rd      1st 2nd 3rd      1st 2nd 3rd
## venue
## desert      1   1   1        1   2   0        0   0   3
## ocean       0   1   1        1   1   0        1   0   1
``````