Pandas Pivot Titanic: Find survival rate by gender, age wise of various classes
Pandas: Pivot Titanic Exercise-6 with Solution
Write a Pandas program to create a Pivot table and find survival rate by gender, age wise of various classes. 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', index=['sex','age'], columns='class')
print(result)
Sample Output:
class First Second Third sex age female 0.75 NaN NaN 1.000000 1.00 NaN NaN 1.000000 2.00 0.000000 1.000000 0.250000 3.00 NaN 1.000000 0.000000 4.00 NaN 1.000000 1.000000 5.00 NaN 1.000000 1.000000 6.00 NaN 1.000000 0.000000 7.00 NaN 1.000000 NaN 8.00 NaN 1.000000 0.000000 9.00 NaN NaN 0.000000 10.00 NaN NaN 0.000000 11.00 NaN NaN 0.000000 13.00 NaN 1.000000 1.000000 14.00 1.000000 1.000000 0.500000 14.50 NaN NaN 0.000000 15.00 1.000000 NaN 1.000000 16.00 1.000000 NaN 0.666667 17.00 1.000000 1.000000 0.500000 18.00 1.000000 1.000000 0.375000 19.00 1.000000 1.000000 1.000000 20.00 NaN NaN 0.000000 21.00 1.000000 1.000000 0.250000 22.00 1.000000 1.000000 0.666667 23.00 1.000000 1.000000 0.500000 24.00 1.000000 0.857143 0.750000 25.00 0.000000 1.000000 0.000000 26.00 1.000000 0.000000 0.666667 27.00 NaN 0.666667 1.000000 28.00 NaN 1.000000 0.000000 29.00 1.000000 1.000000 0.333333 ... ... ... ... male 42.00 0.666667 0.333333 0.000000 43.00 NaN 0.000000 0.000000 44.00 0.000000 0.000000 0.250000 45.00 0.250000 NaN 0.500000 45.50 0.000000 NaN 0.000000 46.00 0.000000 0.000000 NaN 47.00 0.000000 0.000000 0.000000 48.00 1.000000 0.000000 0.000000 49.00 0.666667 NaN 0.000000 50.00 0.333333 0.000000 0.000000 51.00 0.500000 0.000000 0.000000 52.00 0.500000 0.000000 NaN 54.00 0.000000 0.000000 NaN 55.00 0.000000 NaN NaN 55.50 NaN NaN 0.000000 56.00 0.333333 NaN NaN 57.00 NaN 0.000000 NaN 58.00 0.000000 NaN NaN 59.00 NaN 0.000000 0.000000 60.00 0.500000 0.000000 NaN 61.00 0.000000 NaN 0.000000 62.00 0.000000 1.000000 NaN 64.00 0.000000 NaN NaN 65.00 0.000000 NaN 0.000000 66.00 NaN 0.000000 NaN 70.00 0.000000 0.000000 NaN 70.50 NaN NaN 0.000000 71.00 0.000000 NaN NaN 74.00 NaN NaN 0.000000 80.00 1.000000 NaN NaN [145 rows x 3 columns]
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 rate by gender on various classes.
Next: Write a Pandas program to partition each of the passengers into four categories based on their age.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics