Giả sử file CSV gốc là SalesRecords.csv với dữ liệu như hình.
Mục tiêu: Tạo 3 file CSV riêng biệt dựa trên tên xe trong cột Car: BMW.csv, Lexus.csv, Jaguar.csv.
Đọc file CSV gốc:
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv") Sử dụng groupby() để tách file theo tên xe:
for (car), group in dataFrame.groupby(['Car']):
group.to_csv(f'{car}.csv', index=False) Ví dụ hoàn chỉnh
import pandas as pd
# Đọc file CSV gốc
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nFile CSV gốc = \n", dataFrame)
# Tách file theo tên xe
for (car), group in dataFrame.groupby(['Car']):
group.to_csv(f'{car}.csv', index=False)
# Hiển thị nội dung các file mới
print("\nCSV 1 = \n", pd.read_csv("BMW.csv"))
print("\nCSV 2 = \n", pd.read_csv("Lexus.csv"))
print("\nCSV 3 = \n", pd.read_csv("Jaguar.csv")) Kết quả
Input CSV file = Unnamed: 0 Car Date_of_Purchase 0 0 BMW 10/10/2020 1 1 Lexus 10/12/2020 2 2 BMW 10/17/2020 3 3 Jaguar 10/16/2020 4 4 Jaguar 10/19/2020 5 5 BMW 10/22/2020 CSV 1 = Unnamed: 0 Car Date_of_Purchase 0 0 BMW 10/10/2020 1 2 BMW 10/17/2020 2 5 BMW 10/22/2020 CSV 2 = Unnamed: 0 Car Date_of_Purchase 0 1 Lexus 10/12/2020 CSV 3 = Unnamed: 0 Car Date_of_Purchase 0 3 Jaguar 10/16/2020 1 4 Jaguar 10/19/2020
3 file CSV được tạo trong thư mục dự án (ví dụ PyCharm):
C:\Users\amit_\PycharmProjects\pythonProject\BMW.csv C:\Users\amit_\PycharmProjects\pythonProject\Jaguar.csv C:\Users\amit_\PycharmProjects\pythonProject\Lexus.csv