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

Trích xuất cột cụ thể từ file CSV thành danh sách trong Python

Để trích xuất cột cụ thể từ CSV, dùng Pandas read_csv().

Các bước

  • Tạo danh sách cột cần trích xuất.
  • Dùng read_csv() đọc CSV vào DataFrame.
  • In dữ liệu trích xuất.
  • Vẽ DataFrame bằng plot().
  • Hiển thị bằng show().

Ví dụ

import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
columns = ["Name", "Marks"]
df = pd.read_csv("input.csv", usecols=columns)
print("Contents in csv file:\n", df)
plt.plot(df.Name, df.Marks)
plt.show()

File CSV chứa dữ liệu:

NameMarks
Arun98
Shyam75
Govind54
Javed92
Raju87

Kết quả

Mã sẽ trích xuất dữ liệu CSV và hiển thị đồ thị:

Trích xuất cột cụ thể từ file CSV thành danh sách trong Python