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

Python - Cách ghi Pandas DataFrame ra file CSV


Để ghi DataFrame ra file CSV trong Python, dùng phương thức to_csv().

Trước tiên, tạo từ điển danh sách:

# dictionary of lists 
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
     'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22']}

Tạo DataFrame:

dataFrame = pd.DataFrame(d)

Ghi ra file CSV (đường dẫn Desktop):

dataFrame.to_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

Ví dụ

import pandas as pd 
# Tạo từ điển 
d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],
     'Date_of_purchase': ['2020-10-10', '2020-10-12', '2020-10-17', '2020-10-16', '2020-10-19', '2020-10-22']} 
# Tạo DataFrame 
dataFrame = pd.DataFrame(d) 
print("DataFrame...\n", dataFrame) 
# Ghi ra CSV 
dataFrame.to_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv") 
print("File CSV đã được ghi thành công...")

Kết quả

DataFrame... 
  Car Date_of_purchase 
0 BMW 2020-10-10 
1 Lexus 2020-10-12 
2 Audi 2020-10-17 
3 Mercedes 2020-10-16 
4 Jaguar 2020-10-19 
5 Bentley 2020-10-22 
The output csv file written successfully and generated...

File SalesRecords.csv được tạo thành công.

Python - Cách ghi Pandas DataFrame ra file CSV