Computer >> Máy Tính >  >> Lập trình >> Python

Python - Cách ghi khung dữ liệu gấu trúc vào tệp CSV

Để ghi khung dữ liệu gấu trúc vào tệp CSV bằng Python, hãy sử dụng to_csv () phương pháp. Đầu tiên, chúng ta hãy tạo một 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']
}

Bây giờ, hãy tạo khung dữ liệu gấu trúc từ danh sách từ điển ở trên -

dataFrame = pd.DataFrame(d)

Tệp CSV đầu ra của chúng tôi sẽ tạo trên Máy tính để bàn vì chúng tôi đã đặt đường dẫn Máy tính để bàn bên dưới -

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

Ví dụ

Sau đây là mã -

import pandas as pd

# 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']
}

# creating dataframe from the above dictionary of lists
dataFrame = pd.DataFrame(d)
print("DataFrame...\n",dataFrame)

# write dataFrame to SalesRecords CSV file
dataFrame.to_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

# display the contents of the output csv
print("The output csv file written successfully and generated...")

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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...

Kết quả “SalesRecords.csv” được tạo thành công với các bản ghi sau, tức là khung dữ liệu gấu trúc -

Python - Cách ghi khung dữ liệu gấu trúc vào tệp CSV