w3resource

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

Pandas: Pivot Titanic Exercise-15 with Solution

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         

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.



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://w3resource.com/python-exercises/pandas/excel/pandas-pivot-titanic-exercise-15.php