Python - 如何將 pandas 資料框寫入 CSV 檔案
要在 Python 中將 pandas 資料框寫入 CSV 檔案,請使用 to_csv() 方法。首先,讓我們建立一個包含列表的字典 -
# 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']
}現在,從上面的列表字典中建立 pandas 資料框 -
dataFrame = pd.DataFrame(d)
因為我們在下面設定了桌面路徑,所以我們輸出的 CSV 檔案將生成在桌面上 -
dataFrame.to_csv("C:\Users\amit_\Desktop\sales1.csv\SalesRecords.csv")示例
如下所示 -
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...")輸出
這將生成以下輸出 -
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...
生成的“SalesRecords.csv”包含以下記錄(即 pandas 資料框):

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP