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 数据框):
广告