w3resource

Pandas Pivot Titanic: Calculate how many women and men were in a particular cabin class


14. Pivot Table: Count Women and Men in Cabin Class (Alternate)

Write a Pandas program to create a Pivot table and calculate how many women and men were in a particular cabin 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=['pclass'], values='survived', aggfunc='count')
print(result)

Sample Output:

pclass    1    2    3
sex                  
female   94   76  144
male    122  108  347           

For more Practice: Solve these Related Problems:

  • Write a Pandas program to create a pivot table that calculates the number of women and men for each cabin class, ensuring no duplicate counts.
  • Write a Pandas program to generate a pivot table from titanic.csv that shows gender distribution per cabin class with a custom aggregation function.
  • Write a Pandas program to build a pivot table that groups cabin classes and returns a count of female and male passengers separately.
  • Write a Pandas program to create a pivot table that provides a cross-tabulation of cabin class and gender with counts for each combination.

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 compute survival totals of all classes along each group.
Next: Write a Pandas program to create a Pivot table and find number of survivors and average rate grouped by gender and class.

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.