Python Pandas - 根據和過濾 DataFrame 中的幾行
要根據和從 DataFrame 中過濾幾行,我們考慮了一個有關學生成績的示例。我們需要計算特定科目的總和,其中總和大於 200,即該特定科目中所有 3 個學生的總和大於 200。透過這種方式,我們可以過濾出總和小於 200 的行。
首先,讓我們建立一個具有 3 列的 DataFrame,即 3 個學生的記錄 -
dataFrame = pd.DataFrame({'Jacob_Marks': [95, 90, 70, 85, 88],'Ted_Marks': [60, 50, 65, 85, 70],'Jamie_Marks': [77, 76, 60, 45, 50]})根據行進行過濾。獲取所有 3 個學生的總和大於 200 的行 -
dataFrame = dataFrame[dataFrame.sum(axis=1) > 200]
示例
以下是完整程式碼 -
import pandas as pd
# create a dataframe with 3 columns
dataFrame = pd.DataFrame({'Jacob_Marks': [95, 90, 70, 85, 88],'Ted_Marks': [60, 50, 65, 85, 70],'Jamie_Marks': [77, 76, 60, 45, 50]})
print"Dataframe...\n",dataFrame
# filtering on the basis of rows
# fetching rows with total greater than 200 for all the 3 students
dataFrame = dataFrame[dataFrame.sum(axis=1) > 200]
# dataframe
print"Updated Dataframe...\n",dataFrame輸出
這將產生以下輸出 -
Dataframe... Jacob_Marks Jamie_Marks Ted_Marks 0 95 77 60 1 90 76 50 2 70 60 65 3 85 45 85 4 88 50 70 Updated Dataframe... Jacob_Marks Jamie_Marks Ted_Marks 0 95 77 60 1 90 76 50 3 85 45 85 4 88 50 70
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP