w3resource

Pandas Pivot Titanic: Count survival by gender, categories wise age of various classes

Pandas: Pivot Titanic Exercise-8 with Solution

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                

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 find survival rate by gender on 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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/excel/pandas-pivot-titanic-exercise-8.php