w3resource

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

Pandas: Pivot Titanic Exercise-14 with Solution

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           

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.



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://198.211.115.131/python-exercises/pandas/excel/pandas-pivot-titanic-exercise-14.php