w3resource

Pandas Pivot Titanic: Find survival rate by gender, age of the different categories of various classes


9. Pivot Table: Survival Rate by Gender and Age Categories

Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. Go to Editor

Sample Solution:

Python Code :

import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
age = pd.cut(df['age'], [0, 20, 55])
result = df.pivot_table('survived', index=['sex', age], columns='class')
print(result)

Sample Output:

class               First    Second     Third
sex    age                                   
female (0, 20]   0.928571  1.000000  0.510638
       (20, 55]  0.968750  0.912281  0.407407
male   (0, 20]   0.571429  0.526316  0.197368
       (20, 55]  0.440000  0.054054  0.134503              

For more Practice: Solve these Related Problems:

  • Write a Pandas program to create a pivot table that calculates survival rates by gender and by the defined age categories.
  • Write a Pandas program to generate a pivot table showing the percentage of survivors within each gender and age group.
  • Write a Pandas program to build a pivot table that normalizes survival data by both gender and age category.
  • Write a Pandas program to create a pivot table from titanic.csv to display survival rate ratios across gender and age group intersections.

Python Code Editor:


Pivot Titanic.csv:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to create a Pivot table and count survival by gender, categories wise age of various classes.
Next: Write a Pandas program to create a Pivot table and find survival rate by gender, age of the different categories of various classes. Add the fare as a dimension of columns and partition fare column into 2 categories based on the values present in fare columns.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.