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

Python Pandas: อ่าน CSV และกรองคอลัมน์ product ที่เป็น 'Car' ใน 10 แถวแรก


โจทย์

สมมติมีไฟล์ products.csv ข้อมูล 100 แถว 8 คอลัมน์ ต้องการอ่านข้อมูล แล้วกรองเฉพาะ 10 แถวแรกที่คอลัมน์ 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

วิธีที่ 1: ใช้ iloc

  • อ่าน CSV มาเก็บใน DataFrame df
  • แสดงจำนวนแถวและคอลัมน์ด้วย df.shape
  • เลือก 10 แถวแรกด้วย df.iloc[0:10, :] เก็บใน df1
  • กรองคอลัมน์ product (index=1) ที่เท่ากับ 'Car' ด้วย 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: ใช้ head() และชื่อคอลัมน์

  • อ่าน CSV มาเก็บใน df
  • แสดงขนาดข้อมูล
  • เลือก 10 แถวแรกด้วย df.head(10) เก็บใน df1
  • กรองด้วยชื่อคอลัมน์โดยตรง: 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