Write a Python program to count the total number of ages between 20 to 30 in a DataFrame



Input

Assume, you have a DataFrame,

 Id Age
0 1 21
1 2 23
2 3 32
3 4 35
4 5 18

Output

Total number of age between 20 to 30 is 2.

Solution

To solve this, we will follow the below approaches.

  • Define a DataFrame

  • Set the DataFrame Age column between 20,30. Store it in result DataFrame. It is defined below,

df[df['Age'].between(20,30)]
  • Finally, calculate the length of the result.

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
data = {'Id':[1,2,3,4,5],'Age':[21,23,32,35,18]}
df = pd.DataFrame(data)
print(df)
print("Count the age between 20 to 30")
result = df[df['Age'].between(20,30)]
print(len(result))

Output

 Id Age
0 1 21
1 2 23
2 3 32
3 4 35
4 5 18
Count the age between 20 to 30
2

Advertisements