w3resource

Pandas Pivot Titanic: Partition each of the passengers into four categories based on their age

Pandas: Pivot Titanic Exercise-7 with Solution

Write a Pandas program to partition each of the passengers into four categories based on their age. Go to Editor

Note: Age categories (0, 10), (10, 30), (30, 60), (60, 80)

Sample Solution:

Python Code :

import pandas as pd
import numpy as np
df = pd.read_csv('titanic.csv')
result = pd.cut(df['age'], [0, 10, 30, 60, 80])
print(result)

Sample Output:

0      (10, 30]
1      (30, 60]
2      (10, 30]
3      (30, 60]
4      (30, 60]
5           NaN
6      (30, 60]
7       (0, 10]
8      (10, 30]
9      (10, 30]
10      (0, 10]
11     (30, 60]
12     (10, 30]
13     (30, 60]
14     (10, 30]
15     (30, 60]
16      (0, 10]
17          NaN
18     (30, 60]
19          NaN
20     (30, 60]
21     (30, 60]
22     (10, 30]
23     (10, 30]
24      (0, 10]
25     (30, 60]
26          NaN
27     (10, 30]
28          NaN
29          NaN
         ...   
861    (10, 30]
862    (30, 60]
863         NaN
864    (10, 30]
865    (30, 60]
866    (10, 30]
867    (30, 60]
868         NaN
869     (0, 10]
870    (10, 30]
871    (30, 60]
872    (30, 60]
873    (30, 60]
874    (10, 30]
875    (10, 30]
876    (10, 30]
877    (10, 30]
878         NaN
879    (30, 60]
880    (10, 30]
881    (30, 60]
882    (10, 30]
883    (10, 30]
884    (10, 30]
885    (30, 60]
886    (10, 30]
887    (10, 30]
888         NaN
889    (10, 30]
890    (30, 60]
Name: age, Length: 891, dtype: category
Categories (4, interval[int64]): [(0, 10] < (10, 30] < (30, 60] < (60, 80]]                

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, age wise of various classes.
Next: Write a Pandas program to create a Pivot table and count survival by gender, categories wise age of various classes.

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