Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - วิธีใช้ Property shape ของ DataFrame

เขียนโปรแกรม Python อ่านข้อมูลจาก products.csv และพิมพ์จำนวน Rows และ Columns แล้วพิมพ์ค่า Column 'product' ที่ตรงกับ 'Car' สำหรับ 10 แถวแรก

สมมติว่ามีไฟล์ 'products.csv' และผลลัพธ์สำหรับจำนวน Rows, Columns และ 'product' ที่ตรง 'Car' 10 แถวแรก:

ดาวน์โหลด 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

เรามี 2 วิธีแก้ปัญหานี้

วิธีที่ 1 (Solution 1)

  • อ่านข้อมูลจาก products.csv และกำหนดให้ df

df = pd.read_csv('products.csv ')
  • พิมพ์จำนวน Rows = df.shape[0] และ Columns = df.shape[1]

  • ตั้ง df1 ให้ Filter 10 แถวแรกจาก df โดยใช้ iloc[0:10,:]

df1 = df.iloc[0:10,:]
  • คำนวณค่า Column Product ที่ตรงกับ Car โดยใช้ df1.iloc[:,1]

ที่นี่ Product Column Index คือ 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

วิธีที่ 2 (Solution 2)

  • อ่านข้อมูลจาก products.csv และกำหนดให้ df

df = pd.read_csv('products.csv ')
  • พิมพ์จำนวน Rows = df.shape[0] และ Columns = df.shape[1]

  • เอา 10 แถวแรกด้วย df.head(10) และกำหนดให้ df1

df1 = df.head(10)
  • เอาค่า Product Column ที่ตรง 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