編寫一個 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP