Menu

Saving and Exporting Processed Data

Saving and Exporting Processed Data

After cleaning or analyzing a dataset, you may need to save the results for another application, report, or analytical workflow. Pandas supports exporting DataFrames to several formats.

Exporting to CSV

import pandas as pd
df = pd.DataFrame({
"Product": ["Laptop", "Phone", "Tablet"],
"Sales": [55000, 30000, 25000]
})
df.to_csv("processed_sales.csv", index=False)

The index=False argument prevents Pandas from writing the DataFrame index as an additional column.

Exporting to Excel

df.to_excel(
"processed_sales.xlsx",
index=False,
sheet_name="Sales"
)

You may need the openpyxl package to write an .xlsx file.

Excel exports are useful when sharing results with people who work primarily with spreadsheets.

Writing Data to a Database

You can also save a DataFrame to a database table using to_sql().

import sqlite3
import pandas as pd
df = pd.DataFrame({
"Product": ["Laptop", "Phone", "Tablet"],
"Sales": [55000, 30000, 25000]
})
connection = sqlite3.connect("business.db")
df.to_sql(
"processed_sales",
connection,
if_exists="replace",
index=False
)
connection.close()

The if_exists parameter controls what happens when the table already exists:

  • fail: Raise an error if the table exists.
  • replace: Drop the existing table and create a new one.
  • append: Add the new records to the existing table.

Use replace carefully because it removes the existing table and its data before creating the replacement. In real applications, confirm the intended table behavior before writing data. <Cite refs={["turn954920search1","turn954920search6"]}/>


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details