Pandas Pivot Titanic: Count survival by gender, categories wise age of various classes
8. Pivot Table: Count Survival by Gender and Age Categories
Write a Pandas program to create a Pivot table and count survival by gender, categories wise age of various classes. Go to Editor
Note: Age categories (0, 10), (10, 30), (30, 60), (60, 80)
Sample Solution:
Python Code :
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
age = pd.cut(df['age'], [0, 10, 30, 60, 80])
result = df.pivot_table('survived', index=['sex',age], columns='pclass', aggfunc='count')
print(result)
Sample Output:
pclass              1     2      3
sex    age                        
female (0, 10]    1.0   8.0   22.0
       (10, 30]  34.0  36.0   57.0
       (30, 60]  48.0  30.0   22.0
       (60, 80]   2.0   NaN    1.0
male   (0, 10]    2.0   9.0   22.0
       (10, 30]  24.0  43.0  151.0
       (30, 60]  63.0  44.0   76.0
       (60, 80]  12.0   3.0    4.0                
For more Practice: Solve these Related Problems:
- Write a Pandas program to create a pivot table from titanic.csv that counts survivors by gender within each defined age category.
- Write a Pandas program to generate a pivot table that aggregates survival counts by gender and the four age partitions.
- Write a Pandas program to build a pivot table that displays the number of survivors grouped by gender and custom age intervals.
- Write a Pandas program to create a pivot table showing survival counts for each combination of gender and age group in titanic.csv.
Go to:
PREV : Partition Passengers into Age Categories.
NEXT : Pivot Table: Survival Rate by Gender and Age Categories. 
Python Code Editor:
Pivot Titanic.csv:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
