Pandas Pivot Titanic: Create a Pivot table and find survival of both gender and class affected
12. Pivot Table: Survival by Gender and Class
Write a Pandas program to create a Pivot table and find survival of both gender and class affected. Go to Editor
Sample Solution:
Python Code :
import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = df.groupby(['sex', 'class'])['survived'].aggregate('mean').unstack()
print(result)
Sample Output:
class First Second Third sex female 0.968085 0.921053 0.500000 male 0.368852 0.157407 0.135447
For more Practice: Solve these Related Problems:
- Write a Pandas program to create a pivot table that displays survival counts grouped by both gender and cabin class.
- Write a Pandas program to generate a pivot table that shows the effect of gender and class on survival using titanic.csv.
- Write a Pandas program to build a pivot table to analyze survival data segmented by gender and class simultaneously.
- Write a Pandas program to create a pivot table that cross-tabulates survival outcomes with gender and cabin class.
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 calculate number of women and men were in a particular cabin class.
Next: Write a Pandas program to create a Pivot table and compute survival totals of all classes along each group.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.