w3resource

Pandas Pivot Titanic: Separate the gender according to whether they traveled alone or not to get the probability of survival

Pandas: Pivot Titanic Exercise-18 with Solution

Write a Pandas program to create a Pivot table and separate the gender according to whether they traveled alone or not to get the probability of survival. 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' , [ 'sex' , 'alone' ] , 'class' )
print(result)

Sample Output:

class            First    Second     Third
sex    alone                              
female False  0.966667  0.931818  0.416667
       True   0.970588  0.906250  0.616667
male   False  0.425532  0.277778  0.180723
       True   0.333333  0.097222  0.121212

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 gender wise sum of survival and cabin class wise mean value of fare.
Next: Write a Pandas program to create a Pivot table and find the probability of survival by class, gender, solo boarding and port of embarkation.

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-18.php