w3resource

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


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              

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.