📄 Exporting Data (CSV, Excel, JSON)
Exporting your analyzed data to different file formats is essential for sharing results and creating reports! Whether you need a simple CSV for data exchange, a formatted Excel file for business presentations, or JSON for web applications, pandas makes it easy.
Think of exporting like translating your analysis into different languages that various tools and people can understand.
import pandas as pd
# Sample analysis results
sales_report = pd.DataFrame({
'product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor'],
'q1_sales': [25, 150, 75, 40],
'q2_sales': [30, 180, 85, 45],
'total_revenue': [55000, 8250, 12000, 17000]
})
print("Sales report to export:")
print(sales_report)
print()
# Export to CSV
sales_report.to_csv('sales_report.csv', index=False)
print("✅ Exported to CSV: sales_report.csv")
# Export to Excel
sales_report.to_excel('sales_report.xlsx', index=False)
print("✅ Exported to Excel: sales_report.xlsx")
# Export to JSON
sales_report.to_json('sales_report.json', orient='records', indent=2)
print("✅ Exported to JSON: sales_report.json")
📄 CSV Export
CSV (Comma-Separated Values) is the most universal data format:
Basic CSV Export
import pandas as pd
# Customer data
customers = pd.DataFrame({
'customer_id': [1001, 1002, 1003, 1004],
'name': ['Alice Johnson', 'Bob Smith', 'Charlie Brown', 'Diana Wilson'],
'total_orders': [8, 12, 5, 15],
'total_spent': [2450.75, 3890.25, 1205.50, 4560.00]
})
print("Customer data:")
print(customers)
print()
# Basic CSV export
customers.to_csv('customers.csv', index=False)
print("✅ Saved basic CSV")
# CSV with custom options
customers.to_csv('customers_formatted.csv',
index=False,
float_format='%.2f', # Format numbers to 2 decimal places
encoding='utf-8') # Handle special characters
print("✅ Saved formatted CSV")
# Verify the export
loaded_data = pd.read_csv('customers.csv')
print("\nVerification - loaded CSV:")
print(loaded_data)
Handling Special Cases
import pandas as pd
import numpy as np
# Data with missing values and special characters
messy_data = pd.DataFrame({
'product_name': ['Laptop Pro', 'Mouse™', 'Keyboard & Stand', 'Monitor"'],
'price': [1299.99, np.nan, 89.50, 345.00],
'description': ['High-end laptop', None, 'Wireless,bluetooth', 'Large screen']
})
print("Data with missing values and special characters:")
print(messy_data)
print()
# Export with custom handling
messy_data.to_csv('messy_data.csv',
index=False,
na_rep='Missing', # Replace NaN with 'Missing'
quoting=1, # Quote fields with special characters
encoding='utf-8') # Handle unicode characters
print("✅ Exported messy data with proper handling")
# Load and verify
loaded_messy = pd.read_csv('messy_data.csv')
print("\nLoaded messy data:")
print(loaded_messy)
📊 Excel Export
Excel files are perfect for business reports and presentations:
Basic Excel Export
import pandas as pd
# Department performance data
performance = pd.DataFrame({
'department': ['Sales', 'Marketing', 'IT', 'HR'],
'employees': [25, 15, 20, 8],
'budget': [250000, 180000, 300000, 120000],
'actual_spend': [245000, 175000, 285000, 115000]
})
# Calculate variance
performance['variance'] = performance['actual_spend'] - performance['budget']
performance['variance_pct'] = (performance['variance'] / performance['budget'] * 100).round(1)
print("Department performance:")
print(performance)
print()
# Export to Excel with custom sheet name
performance.to_excel('department_performance.xlsx',
sheet_name='Q1_Performance',
index=False)
print("✅ Exported to Excel with custom sheet name")
# Verify the export
loaded_excel = pd.read_excel('department_performance.xlsx', sheet_name='Q1_Performance')
print("\nVerification - loaded Excel:")
print(loaded_excel)
Multiple Sheets in Excel
import pandas as pd
# Create related datasets
summary = pd.DataFrame({
'metric': ['Total Revenue', 'Total Orders', 'Average Order Value'],
'value': [285000, 1150, 247.83]
})
monthly_sales = pd.DataFrame({
'month': ['January', 'February', 'March'],
'revenue': [95000, 85000, 105000],
'orders': [380, 350, 420]
})
top_products = pd.DataFrame({
'product': ['Laptop', 'Monitor', 'Keyboard', 'Mouse'],
'revenue': [125000, 85000, 45000, 30000]
})
print("Summary data:")
print(summary)
print("\nMonthly sales:")
print(monthly_sales)
print("\nTop products:")
print(top_products)
# Export multiple sheets to one Excel file
with pd.ExcelWriter('quarterly_report.xlsx') as writer:
summary.to_excel(writer, sheet_name='Summary', index=False)
monthly_sales.to_excel(writer, sheet_name='Monthly_Sales', index=False)
top_products.to_excel(writer, sheet_name='Top_Products', index=False)
print("\n✅ Created Excel file with 3 sheets: quarterly_report.xlsx")
🌐 JSON Export
JSON is perfect for web applications and APIs:
Basic JSON Export
import pandas as pd
# Product catalog
products = pd.DataFrame({
'id': [1, 2, 3, 4],
'name': ['Laptop Pro', 'Wireless Mouse', 'Mechanical Keyboard', '4K Monitor'],
'category': ['Computers', 'Accessories', 'Accessories', 'Monitors'],
'price': [1299.99, 49.99, 129.99, 399.99],
'in_stock': [True, True, False, True]
})
print("Product catalog:")
print(products)
print()
# Export to JSON (records format - most common)
products.to_json('products.json', orient='records', indent=2)
print("✅ Exported to JSON (records format)")
# Export to JSON (index format)
products.to_json('products_index.json', orient='index', indent=2)
print("✅ Exported to JSON (index format)")
# Read and display the JSON content
with open('products.json', 'r') as f:
json_content = f.read()
print("\nJSON content (first 200 characters):")
print(json_content[:200] + "...")
JSON with Date Data
import pandas as pd
# Sales data with dates
sales_data = pd.DataFrame({
'sale_date': pd.to_datetime(['2023-01-15', '2023-01-20', '2023-01-25']),
'customer': ['Alice', 'Bob', 'Charlie'],
'amount': [299.99, 149.50, 89.99],
'product': ['Laptop', 'Monitor', 'Keyboard']
})
print("Sales data with dates:")
print(sales_data)
print()
# Export with proper date formatting
sales_data.to_json('sales_with_dates.json',
orient='records',
date_format='iso', # ISO date format
indent=2)
print("✅ Exported JSON with proper date formatting")
# Verify by loading back
loaded_json = pd.read_json('sales_with_dates.json', orient='records')
print("\nLoaded from JSON:")
print(loaded_json)
print("Date column type:", loaded_json['sale_date'].dtype)
🔧 Export Options and Customization
Fine-tune your exports for specific needs:
📋 Real-World Export Example
Let's create a comprehensive business report export:
import pandas as pd
# Comprehensive business analysis
regional_performance = pd.DataFrame({
'region': ['North', 'South', 'East', 'West'],
'revenue': [180000, 165000, 195000, 170000],
'customers': [720, 658, 780, 680],
'avg_order_value': [250.00, 250.76, 250.00, 250.00]
})
customer_segments = pd.DataFrame({
'segment': ['Premium', 'Standard', 'Basic'],
'count': [425, 1230, 1183],
'avg_lifetime_value': [2850, 1245, 485],
'retention_rate': [0.92, 0.78, 0.65]
})
# Calculate additional metrics
regional_performance['revenue_per_customer'] = (
regional_performance['revenue'] / regional_performance['customers']
).round(2)
customer_segments['total_value'] = (
customer_segments['count'] * customer_segments['avg_lifetime_value']
)
print("Regional performance:")
print(regional_performance)
print("\nCustomer segments:")
print(customer_segments)
# Export to multiple formats for different stakeholders
# 1. CSV for data team
regional_performance.to_csv('regional_performance.csv', index=False)
customer_segments.to_csv('customer_segments.csv', index=False)
# 2. Excel for management
with pd.ExcelWriter('business_report.xlsx') as writer:
regional_performance.to_excel(writer, sheet_name='Regional_Performance', index=False)
customer_segments.to_excel(writer, sheet_name='Customer_Segments', index=False)
# 3. JSON for web dashboard
regional_performance.to_json('regional_data.json', orient='records', indent=2)
print("\n✅ Exported complete business report:")
print(" 📄 CSV files for data team")
print(" 📊 Excel file for management")
print(" 🌐 JSON file for web dashboard")
🎯 Key Takeaways
🚀 What's Next?
Excellent! You now know how to export data to the most common file formats. Next, let's learn about database export - saving data back to databases for integration with other systems.
Continue to: Database Export
Keep exporting! 📄💾
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.