💾 Saving Your Work

After all your hard work analyzing and transforming data, you need to save and share your results! Pandas provides excellent tools for exporting data to various formats - from simple CSV files to Excel spreadsheets with multiple sheets, and even back to databases.

Think of saving data like packaging your findings for different audiences - some prefer Excel files, others need CSV data, and databases want structured imports.

import pandas as pd

# Sample analyzed data
sales_summary = pd.DataFrame({
    'region': ['North', 'South', 'East', 'West'],
    'total_sales': [150000, 120000, 180000, 140000],
    'avg_order': [285, 340, 275, 320],
    'customer_count': [526, 353, 655, 438]
})

print("Sales summary to save:")
print(sales_summary)
print()

# Save to CSV
sales_summary.to_csv('sales_summary.csv', index=False)
print("✅ Saved to CSV file: sales_summary.csv")

# Save to Excel
sales_summary.to_excel('sales_summary.xlsx', index=False)
print("✅ Saved to Excel file: sales_summary.xlsx")

# Check the saved file
saved_data = pd.read_csv('sales_summary.csv')
print("\nVerifying saved CSV:")
print(saved_data)

🎯 Why Save Data?

Sharing and preserving your analysis results is crucial:

📚 What You'll Learn in This Section

Master essential data export techniques:

🛠️ Export Format Overview

Different formats serve different purposes:

📊 Quick Export Examples

Here's a preview of exporting to different formats:

import pandas as pd

# Create sample business data
quarterly_report = pd.DataFrame({
    'quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
    'revenue': [125000, 145000, 135000, 165000],
    'expenses': [95000, 110000, 105000, 120000],
    'profit': [30000, 35000, 30000, 45000]
})

print("Quarterly report:")
print(quarterly_report)
print()

# Calculate profit margin
quarterly_report['profit_margin'] = (
    quarterly_report['profit'] / quarterly_report['revenue'] * 100
).round(1)

print("With calculated profit margin:")
print(quarterly_report)
print()

# Save in multiple formats
quarterly_report.to_csv('quarterly_report.csv', index=False)
quarterly_report.to_excel('quarterly_report.xlsx', index=False, sheet_name='Summary')
quarterly_report.to_json('quarterly_report.json', orient='records', indent=2)

print("✅ Exported to:")
print("  - CSV: quarterly_report.csv")
print("  - Excel: quarterly_report.xlsx")
print("  - JSON: quarterly_report.json")

Excel with Multiple Sheets

import pandas as pd

# Create multiple related datasets
summary = pd.DataFrame({
    'metric': ['Total Revenue', 'Total Customers', 'Avg Order Value'],
    'value': [590000, 1972, 299.19]
})

by_region = pd.DataFrame({
    'region': ['North', 'South', 'East', 'West'],
    'revenue': [150000, 120000, 180000, 140000]
})

by_month = pd.DataFrame({
    'month': ['Jan', 'Feb', 'Mar', 'Apr'],
    'revenue': [145000, 155000, 140000, 150000]
})

print("Summary data:")
print(summary)
print("\nRegion data:")
print(by_region)
print("\nMonth data:")
print(by_month)

# Save multiple sheets to one Excel file
with pd.ExcelWriter('complete_report.xlsx') as writer:
    summary.to_excel(writer, sheet_name='Summary', index=False)
    by_region.to_excel(writer, sheet_name='By_Region', index=False)
    by_month.to_excel(writer, sheet_name='By_Month', index=False)

print("\n✅ Saved multi-sheet Excel: complete_report.xlsx")

🔧 Export Best Practices

Essential practices for clean, professional exports:

📈 Real-World Export Scenarios

Common business export situations:

import pandas as pd

# Customer analysis results
customer_analysis = pd.DataFrame({
    'customer_segment': ['Premium', 'Standard', 'Basic'],
    'customer_count': [245, 892, 1156],
    'avg_lifetime_value': [2850.75, 1245.30, 485.20],
    'churn_rate_percent': [5.2, 12.8, 18.7]
})

# Product performance
product_performance = pd.DataFrame({
    'product_category': ['Electronics', 'Books', 'Clothing', 'Home'],
    'units_sold': [1250, 3400, 2100, 800],
    'revenue': [245000, 85000, 126000, 95000],
    'return_rate_percent': [3.2, 1.1, 8.5, 4.2]
})

print("Customer analysis:")
print(customer_analysis)
print("\nProduct performance:")
print(product_performance)

# Create executive summary
executive_summary = pd.DataFrame({
    'key_metric': [
        'Total Customers',
        'Average Customer Value',
        'Top Product Category',
        'Overall Return Rate'
    ],
    'value': [
        f"{customer_analysis['customer_count'].sum():,}",
        f"${customer_analysis['avg_lifetime_value'].mean():.2f}",
        product_performance.loc[product_performance['revenue'].idxmax(), 'product_category'],
        f"{(product_performance['return_rate_percent'].mean()):.1f}%"
    ]
})

print("\nExecutive summary:")
print(executive_summary)

# Export comprehensive report
with pd.ExcelWriter('business_analysis_report.xlsx') as writer:
    executive_summary.to_excel(writer, sheet_name='Executive_Summary', index=False)
    customer_analysis.to_excel(writer, sheet_name='Customer_Analysis', index=False)
    product_performance.to_excel(writer, sheet_name='Product_Performance', index=False)

print("\n✅ Complete business report saved to: business_analysis_report.xlsx")

🎯 Export Workflow

Professional data export workflow:

🚀 What's Next?

Ready to start saving and sharing your data analysis results? Let's begin with the most common export formats - CSV, Excel, and JSON.

Start with: Exporting Data (CSV, Excel, JSON)

Time to save your work! 💾📊

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent