Learn Pandas · 13/14

Exporting and Saving Your Work

7 min read

You've worked hard to clean, process, and analyze your data in a Pandas DataFrame. It's a masterpiece! But right now, it only exists in your computer's temporary memory (RAM). If you close your program or restart your computer, all that work will vanish into thin air. 💨

The Problem: How do you permanently save your DataFrame so you can share it, reload it later, or use it in another application?

The Solution: Pandas provides a fantastic set of functions to export your data into a wide variety of common file formats. Think of it as telling your program, "Okay, you've organized all the ingredients and recipes in your head (the DataFrame), now write them down on a recipe card (a file) so you don't forget."

In this guide, we'll cover the most common and industry-standard ways to save your work.


1. Saving to CSV: to_csv() Best Practices 📝

A CSV (Comma-Separated Values) file is the most universal format for tabular data. It's a simple text file where each row is a new line and columns are separated by a comma. You can open it with almost any data software, from Excel to Google Sheets to another Python script.

Let's say we have this DataFrame:

python
import pandas as pd

data = {'product_id': [101, 102, 103],
        'product_name': ['Laptop', 'Mouse', 'Keyboard'],
        'price': [1200, 25, 75]}
df = pd.DataFrame(data)

The most basic way to save it is:

python
df.to_csv('products.csv')

This works, but it creates a common problem. If you open products.csv, you'll see this:

arduino
,product_id,product_name,price
0,101,Laptop,1200
1,102,Mouse,25
2,103,Keyboard,75

Problem: What's that first column with 0, 1, 2 and no name? That's the DataFrame's index. Pandas saves it by default, but you usually don't want it in your final file. It's like an uninvited guest at your data party.

Solution: The index=False argument is your best friend. This is the industry-standard way to save a CSV.

python
# The right way to save a CSV
df.to_csv('products_cleaned.csv', index=False)

Now, your file products_cleaned.csv looks perfect:

apache
product_id,product_name,price
101,Laptop,1200
102,Mouse,25
103,Keyboard,75

✨ Interesting Fact: While "CSV" stands for comma-separated, some regions in the world (especially in Europe) use a semicolon (;) as a separator because the comma is used as a decimal point (e.g., €10,50). If you need to create a file for a colleague in Germany, you might do this: df.to_csv('products.csv', index=False, sep=';').


2. Exporting to Excel Workbooks 📊

Sometimes, a CSV isn't enough. Your manager might want the data in a familiar Excel .xlsx file, maybe with different tables on separate sheets.

The Problem: How do you save your DataFrame directly into an Excel file, and how can you save multiple DataFrames into different sheets within the same file?

First, you'll need a library that Pandas uses under the hood to handle Excel files. The most common one is openpyxl.

Installation:
You'll need to install it first. Run this command in your terminal:

bash
pip install openpyxl

Saving a Single DataFrame
Saving to Excel is just as easy as saving to a CSV.

python
# Make sure you have openpyxl installed
df.to_excel('products.xlsx', sheet_name='Product_List', index=False)

Here, we again use index=False for good practice and give the sheet a descriptive name using sheet_name.

Saving Multiple DataFrames to Different Sheets
This is a real-world lifesaver. Imagine you have a second DataFrame with inventory data:

python
inventory_data = {'product_id': [101, 102, 103],
                  'stock': [50, 250, 120]}
inventory_df = pd.DataFrame(inventory_data)

To save both df and inventory_df in the same workbook, you need to use the ExcelWriter. Think of the ExcelWriter as opening a new, empty Excel workbook that you can add sheets to one by one before saving and closing it.

python
with pd.ExcelWriter('product_report.xlsx') as writer:
    df.to_excel(writer, sheet_name='Prices', index=False)
    inventory_df.to_excel(writer, sheet_name='Inventory', index=False)

This code creates a single file, product_report.xlsx, with two neat sheets inside: "Prices" and "Inventory". This is incredibly useful for creating organized reports.


3. Writing Back to SQL Databases 🗄️

For more robust, permanent storage, especially when working with web applications or large-scale data systems, you'll often save your results back to a SQL database.

The Problem: You've processed data in Pandas and now need to put the clean result into a database table for other applications to use.

Pandas uses a library called SQLAlchemy to act as a universal translator for different types of SQL databases (like PostgreSQL, MySQL, SQLite, etc.).

Installation:
You'll need SQLAlchemy and potentially a driver for your specific database. For this example, we'll use SQLite, which is built into Python, so you only need SQLAlchemy.

bash
pip install sqlalchemy

Creating a Database Connection
First, you need to create an "engine" that connects to your database. It's like dialing the right phone number to reach your database.

python
from sqlalchemy import create_engine

# Create an engine for a SQLite database file named 'mystore.db'
# This file will be created automatically if it doesn't exist.
engine = create_engine('sqlite:///mystore.db')

Using to_sql()
The to_sql() function is powerful and has one very important argument: if_exists. This tells Pandas what to do if a table with the same name already exists in the database.

  • if_exists='fail': (Default) Throws an error. This is a safe option to prevent you from accidentally overwriting data.
  • if_exists='replace': Deletes the old table and its data, then creates a new one with your DataFrame's data. Use with caution!
  • if_exists='append': Adds the data from your DataFrame to the end of the existing table. Perfect for adding new records.
python
# Let's save our products DataFrame to a table named 'products'
df.to_sql('products', con=engine, if_exists='replace', index=False)

print("Data written to SQL database successfully!")

This is a common workflow: pull data from a database, clean it in Pandas, and write the clean version back to a new table.


4. Modern Formats: Saving as Parquet or JSON ⚡

While CSV and Excel are great for humans, other formats are optimized for machine-to-machine communication or big data workflows.

Parquet: For Speed and Size

The Problem: Your DataFrame has millions of rows. A CSV file would be huge and slow to read. How can you save it more efficiently?

Solution: Parquet. It's a "columnar" storage format.

  • Real-World Analogy: Imagine a phone book. A normal format (like CSV) stores it row by row: (John, Doe, 555-1234), (Jane, Smith, 555-5678). If you want to find all the people named "John," you have to read through every single entry. A columnar format (like Parquet) stores all the first names together, all the last names together, etc: (John, Jane, ...), (Doe, Smith, ...), (555-1234, 555-5678, ...). If you want all the "Johns," you only need to look in the highly optimized "first name" column, which is incredibly fast and compresses very well.

Installation:
You'll need a library like pyarrow to work with Parquet files.

bash
pip install pyarrow

Usage:
Saving to Parquet is incredibly simple:

python
df.to_parquet('products.parquet')

# Reading it back is just as easy and fast!
reloaded_df = pd.read_parquet('products.parquet')

For data science tasks where you save intermediate results, Parquet is the industry standard. It results in smaller files and much faster read/write times.

JSON: For the Web

The Problem: You need to send your data to a web application or an API. The universal language of the web is JSON (JavaScript Object Notation).

Solution: to_json(). This method can format your DataFrame in several ways using the orient parameter.

python
# The 'records' orient is very common for APIs
# It creates a list of dictionaries.
json_output = df.to_json(orient='records')

print(json_output)
# Output:
# [{"product_id":101,"product_name":"Laptop","price":1200},
#  {"product_id":102,"product_name":"Mouse","price":25},
#  {"product_id":103,"product_name":"Keyboard","price":75}]

The orient='records' format is clean, easy for web developers to work with, and a very common way to transfer data from a data backend to a front-end application.


📚 References for Extra Reading

Challenge

You are a data analyst finalizing a sales report. Your task is to export your processed data into various formats for different stakeholders using pandas. You have been provided with several DataFrames: processed_sales, regional_summary, category_summary, high_value_sales, and unprocessed_data.

Your goal is to write the Python code to perform the following four export operations:

  1. For the Data Science Team: Save the main processed_sales DataFrame to a high-performance, columnar storage file named processed_sales_data.parquet.

  2. For Management: Create a single Excel report named management_report.xlsx that contains two separate worksheets. The first sheet, named Regional_Summary, should contain the regional_summary data. The second sheet, named Category_Summary, should contain the category_summary data. The DataFrame index should not be included in the Excel file.

  3. For a Web API: Export the high_value_sales DataFrame to a JSON file named high_value_sales.json. The JSON output must be structured as a list of records to be easily consumable by a web application.

  4. For Archiving: Append the unprocessed_data DataFrame to an existing SQL table named sales_archive using the provided database engine. If the table already contains data, the new data must be added to it without overwriting existing records. The DataFrame index should not be written to the database table.

Expected result

Your final code should correctly implement four different pandas to_* methods based on the requirements.

  1. A call to processed_sales.to_parquet('processed_sales_data.parquet').

  2. The use of pd.ExcelWriter to create management_report.xlsx. Inside a with block, there should be two calls to to_excel:

    • regional_summary.to_excel(writer, sheet_name='Regional_Summary', index=False)
    • category_summary.to_excel(writer, sheet_name='Category_Summary', index=False)
  3. A call to high_value_sales.to_json('high_value_sales.json', orient='records').

  4. A call to unprocessed_data.to_sql('sales_archive', engine, if_exists='append', index=False).

python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.