Python Pandas - 從現有 CSV 檔案建立多個 CSV 檔案
假設下列為我們的 CSV 檔案 -
SalesRecords.csv
我們需要根據上述現有 CSV 檔案生成 3 個 excel 檔案。這 3 個 CSV 檔案需以汽車名稱為基礎,即 BMW.csv、Lexus.csv 和 Jaguar.csv。
首先,讀取我們的輸入 CSV 檔案,即 SalesRecord.csv -
dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv")
使用 groupby() 根據 Car 列中的汽車名稱生成 CSV -
for (car), group in dataFrame.groupby(['Car']): group.to_csv(f'{car}.csv', index=False)
示例
以下是示例程式碼 -
import pandas as pd # DataFrame to read our input CS file dataFrame = pd.read_csv("C:\Users\amit_\Desktop\SalesRecords.csv") print("\nInput CSV file = \n", dataFrame) # groupby to generate CSVs on the basis of Car names in Car column for (car), group in dataFrame.groupby(['Car']): group.to_csv(f'{car}.csv', index=False) #Displaying values of the generated CSVs 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"))
輸出
這將生成以下輸出 -
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 Lexus 10/12/2020 2 5 BMW 10/17/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 個 CSV 檔案。這些 CSV 檔案生成在專案目錄中。在本示例中,這是所有三個 CSV 檔案的路徑,因為我們正在 PyCharm IDE 中執行 -
C:\Users\amit_\PycharmProjects\pythonProject\BMW.csv C:\Users\amit_\PycharmProjects\pythonProject\Jaguar.csv C:\Users\amit_\PycharmProjects\pythonProject\Lexus.csv
廣告