Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python Pandas - Đọc dữ liệu từ file CSV và in giá trị cột 'product' khớp 'Car' cho 10 hàng đầu


Giả sử bạn có file 'products.csv' và kết quả cho một số hàng, cột và giá trị cột 'product' khớp 'Car' cho 10 hàng đầu như sau:

Tải file products.csv tại đây.

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

Chúng ta có hai giải pháp khác nhau cho bài toán này.

Giải pháp 1

  • Đọc dữ liệu từ file products.csv và gán vào df
df = pd.read_csv('products.csv')
  • In số hàng = df.shape[0] và cột = df.shape[1]
  • Thiết lập df1 để lọc 10 hàng đầu từ df bằng iloc[0:10,:]
df1 = df.iloc[0:10,:]
  • Tính giá trị cột product khớp 'Car' bằng df1.iloc[:,1]

Ở đây, chỉ số cột product là 1, và cuối cùng in dữ liệu

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

Ví dụ

Hãy kiểm tra mã sau để hiểu rõ hơn:

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'])

Giải pháp 2

  • Đọc dữ liệu từ file products.csv và gán vào df
df = pd.read_csv('products.csv')
  • In số hàng = df.shape[0] và cột = df.shape[1]
  • Lấy 10 hàng đầu bằng df.head(10) và gán vào df1
df1 = df.head(10)
  • Lấy giá trị cột product khớp 'Car' bằng phương pháp dưới đây
df1[df1['product']=='Car']

Ví dụ

Bây giờ, hãy kiểm tra triển khai để hiểu rõ hơn:

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'])

Đầu ra

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