编写一个 Python 程序来统计一个 DataFrame 中 20 到 30 岁之间的总年龄数
输入-
假设你有一个DataFrame,
Id Age 0 1 21 1 2 23 2 3 32 3 4 35 4 5 18
输出-
Total number of age between 20 to 30 is 2.
解决方案
为了解决这个问题,我们将遵循以下方法。
定义数据帧
将DataFrameAge列设置在20,30之间。将其存储在结果DataFrame中。它定义如下,
df[df['Age'].between(20,30)]
最后,计算结果的长度。
例子
让我们看看下面的实现,以便更好地理解。
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))输出
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
热门推荐
2 破五祝福语简短的
10 简短的爱情生日祝福语
11 幽默祝福语押韵简短
12 对部门师姐祝福语简短
13 退休祝福语简短独特老师
14 新婚宴祝福语简短大全
15 火把节祝福语简短
16 9字祝福语简短创意
17 祝女儿六一祝福语简短
18 送男友2026祝福语简短