0
0
Pandasdata~5 mins

Exporting results to multiple formats in Pandas

Choose your learning style9 modes available
Introduction

We save our data results in different file types to share, use later, or open in other programs.

You want to save a table as a CSV file to open in Excel.
You need to export data as a JSON file to use in a web app.
You want to save your analysis results as an Excel file with multiple sheets.
You need to share data with someone who uses a plain text format.
You want to keep a backup of your data in a simple format.
Syntax
Pandas
df.to_csv('filename.csv')
df.to_excel('filename.xlsx')
df.to_json('filename.json')
df.to_html('filename.html')

Replace 'filename' with your desired file name and extension.

Make sure you have the required libraries installed for Excel export (like openpyxl).

Examples
Saves the DataFrame as a CSV file named 'data.csv'.
Pandas
df.to_csv('data.csv')
Saves the DataFrame as an Excel file named 'data.xlsx'.
Pandas
df.to_excel('data.xlsx')
Saves the DataFrame as a JSON file named 'data.json'.
Pandas
df.to_json('data.json')
Saves the DataFrame as an HTML file named 'data.html'.
Pandas
df.to_html('data.html')
Sample Program

This code creates a small table of names and ages. It then saves this table in four different file types: CSV, Excel, JSON, and HTML. The 'index=False' part means we don't save the row numbers.

Pandas
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Anna', 'Bob', 'Cara'], 'Age': [28, 34, 22]}
df = pd.DataFrame(data)

# Export to CSV
df.to_csv('people.csv', index=False)

# Export to Excel
df.to_excel('people.xlsx', index=False)

# Export to JSON
df.to_json('people.json', orient='records')

# Export to HTML
df.to_html('people.html', index=False)

print('Files saved: people.csv, people.xlsx, people.json, people.html')
OutputSuccess
Important Notes

CSV files are simple and work almost everywhere but don't keep formatting.

Excel files can have multiple sheets and formatting but need extra libraries.

JSON files are great for web apps and data exchange.

Summary

You can save your data in many file types using pandas.

Use to_csv, to_excel, to_json, or to_html depending on your need.

Remember to check if you need extra libraries for some formats like Excel.