Python Pandas - 從資料幀中選擇行子集


要選擇行的子集,請使用條件和提取資料。

假設以下是我們在 Microsoft Excel 中開啟的 CSV 檔案的內容 -

首先,將資料從 CSV 檔案載入到 Pandas DataFrame 中 -

dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")

假設我們想要將“單位”大於 100 的汽車記錄(即行的子集)。為此,使用 -

dataFrame[dataFrame["Units"] > 100]

現在,假設我們想要將“Regular Price”小於 100 的汽車記錄(即行的子集)。為此,使用 -

dataFrame[dataFrame["Reg_Price"] < 3000]

範例

以下是程式碼 -

import pandas as pd

# Load data from a CSV file into a Pandas DataFrame
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesData.csv")
print("\nReading the CSV file...\n",dataFrame)

# displaying two columns
res2 = dataFrame[['Reg_Price','Units']];
print("\nDisplaying two columns : \n",res2)

# selecting a subset of rows
print("\nSelect cars with Units more than 100: \n",dataFrame[dataFrame["Units"] > 100])

# selecting a subset of rows
print("\nSelect cars with Reg_Price less than 3000: \n",dataFrame[dataFrame["Reg_Price"] < 3000])

輸出

這將生成以下輸出 -

Reading the CSV file...
       Car   Reg_Price   Units
0      BMW        2500     100
1    Lexus        3500      80
2     Audi        2500     120
3   Jaguar        2000      70
4  Mustang        2500     110

Displaying only one column Car :
    Reg_Price   Units
0        2500     100
1        3500      80
2        2500     120
3        2000      70
4        2500     110
Name: Car, dtype: object

Select cars with Units more than 100:
       Car   Reg_Price   Units
2     Audi        2500     120
4  Mustang        2500     110

Select cars with Reg_Price less than 3000:
       Car   Reg_Price   Units
0      BMW        2500     100
2     Audi        2500     120
3   Jaguar        2000      70
4  Mustang        2500     110

更新於: 2021 年 9 月 29 日

1k+ 瀏覽量

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.