w3resource

Pandas Pivot Titanic: Compute survival totals of all classes along each group


13. Pivot Table: Survival Totals of All Classes

Write a Pandas program to create a Pivot table and compute survival totals of all classes along each group. 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('survived', index='sex', columns='class', margins=True)
print(result)

Sample Output:

class      First    Second     Third       All
sex                                           
female  0.968085  0.921053  0.500000  0.742038
male    0.368852  0.157407  0.135447  0.188908
All     0.629630  0.472826  0.242363  0.383838           

For more Practice: Solve these Related Problems:

  • Write a Pandas program to create a pivot table that computes the total number of survivors for each passenger class.
  • Write a Pandas program to generate a pivot table that aggregates survival totals across all classes in titanic.csv.
  • Write a Pandas program to build a pivot table displaying the sum of survivors by class, then compare across classes.
  • Write a Pandas program to create a pivot table that summarizes survival counts for every class and verifies the totals with a grand summary.

Go to:


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 calculate how many women and men were in a particular cabin class.

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.



Follow us on Facebook and Twitter for latest update.