Python Pandas – 如何使用 Pandas DataFrame 屬性:shape


編寫一個 Python 程式,從 products.csv 檔案讀取資料,並打印出行數和列數。然後列印“product”列中值為“Car”的前十行的值。

假設您擁有“products.csv”檔案,並且行數和列數以及“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

我們有兩個不同的解決方案來解決這個問題。

方案一

  • products.csv檔案讀取資料並賦值給df

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]計算product列中值為car的資料。

這裡,product列的索引為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'])

輸出

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

方案二

  • products.csv檔案讀取資料並賦值給df

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

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

df1 = df.head(10)
  • 使用以下方法獲取product列中值為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

更新於:2024年2月29日

827 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告