Python Pandas - 從 CSV 檔案讀取資料並列印前十行中與“Car”匹配的“product”列的值


假設您擁有“products.csv”檔案,並且結果包含多行多列,並且前十行中“product”列的值與“Car”匹配。

在此處下載 products.csv 檔案 這裡

Rows: 100 Columns: 8
id    product    engine    avgmileage    price    height_mm    width_mm    productionYear
1 2    Car       Diesel       21         16500       1530          1735         2020
4 5    Car         Gas        18         17450       1530          1780         2018
5 6    Car         Gas        19         15250       1530          1790         2019
8 9    Car        Diesel      23         16925       1530          1800         2018

我們有兩個不同的解決方案可以解決此問題。

解決方案 1

df = pd.read_csv('products.csv ')
  • 列印行數 = df.shape[0] 和列數 = df.shape[1]

  • 將 df1 設定為使用 iloc[0:10,:] 從 df 過濾前十行

df1 = df.iloc[0:10,:]
  • 使用 df1.iloc[:,1] 計算與汽車匹配的產品列值

這裡,產品列索引為 1,最後列印資料

df1[df1.iloc[:,1]=='Car']

示例

讓我們檢查以下程式碼以更好地理解 -

import pandas as pd
df = pd.read_csv('products.csv ')
print("Rows:",df.shape[0],"Columns:",df.shape[1])
df1 = df.iloc[0:10,:]
print(df1[df1.iloc[:,1]=='Car'])

解決方案 2

df = pd.read_csv('products.csv ')
  • 列印行數 = df.shape[0] 和列數 = df.shape[1]

  • 使用 df.head(10) 獲取前十行並分配給 df

df1 = df.head(10)
  • 使用以下方法獲取與 Car 匹配的產品列值

df1[df1['product']=='Car']

示例

現在,讓我們檢查其實現以更好地理解 -

import pandas as pd
df = pd.read_csv('products.csv ')
print("Rows:",df.shape[0],"Columns:",df.shape[1])
df1 = df.head(10)
print(df1[df1['product']=='Car'])

輸出

Rows: 100 Columns: 8
id    product    engine    avgmileage    price    height_mm    width_mm    productionYear
1 2    Car       Diesel       21         16500       1530          1735      2020
4 5    Car       Gas          18         17450       1530          1780      2018
5 6    Car       Gas          19         15250       1530          1790      2019
8 9    Car       Diesel       23         16925       1530          1800      2018

更新於: 2021年2月17日

812 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告