w3resource

Pandas Pivot Titanic: Find number of survivors and average rate grouped by gender and class


15. Pivot Table: Survivors and Average Rate by Gender and Class

Write a Pandas program to create a Pivot table and find number of survivors and average rate grouped by gender and class. Go to Editor

Sample Solution:

Python Code :

import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.pivot_table(index='sex', columns='class', aggfunc={'survived':sum, 'fare':'mean'})
print(result)

Sample Output:

              fare                       survived             
class        First     Second      Third    First Second Third
sex                                                           
female  106.125798  21.970121  16.118810       91     70    72
male     67.226127  19.741782  12.661633       45     17    47         

For more Practice: Solve these Related Problems:

  • Write a Pandas program to create a pivot table that calculates the number of survivors and the average survival rate grouped by gender and class.
  • Write a Pandas program to generate a pivot table from titanic.csv that aggregates survival counts and computes average fare by gender and class.
  • Write a Pandas program to build a pivot table that displays both the survivor count and mean survival rate for each gender-class combination.
  • Write a Pandas program to create a pivot table that summarizes survival totals and average survival rates across gender and class categories.

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 of both gender and class affected.
Next: Write a Pandas program to create a Pivot table and find number of adult male, adult female and children.

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.