Python Pandas- Create multiple CSV files from existing CSV file

PythonServer Side ProgrammingProgramming

Let’s say the following is our CSV file −

SalesRecords.csv

And we need to generate 3 excel files from the above existing CSV file. The 3 CSV files should be on the basis of the Car names i.e. BMW.csv, Lexus.csv and Jaguar.csv.

At first, read our input CSV file i.e. SalesRecord.csv −

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")

Use 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)

Example

Following is the code −

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"))

Output

This will produce the following output −

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

As you can see above, 3 CSV files generated. These CSV files generated in the project directory. In our case the following is the path of all the three CSV files, since we are running on PyCharm IDE −

C:\Users\amit_\PycharmProjects\pythonProject\BMW.csv
C:\Users\amit_\PycharmProjects\pythonProject\Jaguar.csv
C:\Users\amit_\PycharmProjects\pythonProject\Lexus.csv
raja
Published on 04-Oct-2021 07:22:58
Advertisements