編寫一個 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.

解決方案

為解決此問題,我們將採取以下方法。

  • 定義一個 DataFrame

  • 將 DataFrame Age 列設為 20,30 之間。將其儲存在 result DataFrame 中。定義如下,

df[df['Age'].between(20,30)]
  • 最後,計算 result 的長度。

示例

讓我們檢視以下實現,以便更好地理解。

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

更新日期: 2021 年 2 月 24 日

944 次瀏覽

啟動您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.