Why Pandas Instead of Excel Formulas?
Excel is ideal for simple tables, but with larger datasets it quickly becomes unwieldy. With Pandas, you can read, analyze, and statistically evaluate Excel files – reproducibly and automatically.
Installation
pip install pandas openpyxl
openpyxl is required for Excel files (.xlsx).
Reading Excel Files
import pandas as pd
# Read Excel file
df = pd.read_excel('sales_data.xlsx', sheet_name='Revenue')
# First look at the data
print(df.head())
print(df.info())
Important parameters:
sheet_name='Name'– Select specific worksheetusecols='A:E'– Read only specific columnsskiprows=2– Skip first rows
Basic Statistics
# Quick overview
print(df.describe())
# Individual statistics
print(f"Average: ${df['Revenue'].mean():.2f}")
print(f"Median: ${df['Revenue'].median():.2f}")
print(f"Minimum: ${df['Revenue'].min():.2f}")
print(f"Maximum: ${df['Revenue'].max():.2f}")
print(f"Total: ${df['Revenue'].sum():.2f}")
Output:
Average: $15234.56
Median: $12300.00
Minimum: $450.00
Maximum: $89700.00
Total: $2134561.23
Grouped Analysis
# Revenue by product
revenue_by_product = df.groupby('Product')['Revenue'].agg([
('Count', 'count'),
('Total', 'sum'),
('Average', 'mean')
])
print(revenue_by_product)
Result:
Count Total Average
Product
Laptop 45 678900.0 15086.67
Monitor 89 234560.0 2636.18
Keyboard 156 23450.0 150.32
Filtering and Conditions
# Revenue over $10,000
high_revenue = df[df['Revenue'] > 10000]
# Multiple conditions
premium_sales = df[
(df['Revenue'] > 10000) &
(df['Product'] == 'Laptop')
]
# Filter by date
df['Date'] = pd.to_datetime(df['Date'])
q1_2026 = df[(df['Date'] >= '2026-01-01') &
(df['Date'] <= '2026-03-31')]
print(f"Q1 Revenue: ${q1_2026['Revenue'].sum():.2f}")
Monthly Analysis
# Set date as index
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
# Monthly sums
monthly = df.resample('M')['Revenue'].agg([
'sum', 'mean', 'count'
])
print(monthly)
Output:
sum mean count
Date
2026-01-31 456234.50 15207.82 30
2026-02-28 389012.30 14037.60 28
Top/Flop Analysis
# Top 10 revenue
top10 = df.nlargest(10, 'Revenue')[['Product', 'Customer', 'Revenue']]
# Bottom 5
flop5 = df.nsmallest(5, 'Revenue')[['Product', 'Revenue']]
print("Top 10 Deals:")
print(top10)
Writing Results Back to Excel
# Single sheet
revenue_by_product.to_excel('analysis.xlsx', sheet_name='Product Stats')
# Multiple sheets
with pd.ExcelWriter('analysis.xlsx') as writer:
revenue_by_product.to_excel(writer, sheet_name='Products')
monthly.to_excel(writer, sheet_name='Monthly')
top10.to_excel(writer, sheet_name='Top10', index=False)
print("Analysis saved: analysis.xlsx")
Practical Example: Sales Report
import pandas as pd
from datetime import datetime
# Read data
df = pd.read_excel('sales_data.xlsx')
df['Date'] = pd.to_datetime(df['Date'])
# Define period
today = datetime.now()
last_month = today - pd.DateOffset(months=1)
df_month = df[df['Date'] >= last_month]
# Calculate statistics
report = {
'Total Revenue': df_month['Revenue'].sum(),
'Average': df_month['Revenue'].mean(),
'Number of Sales': len(df_month),
'Best Product': df_month.groupby('Product')['Revenue'].sum().idxmax(),
'Top Customer': df_month.groupby('Customer')['Revenue'].sum().idxmax()
}
# As DataFrame for Excel
report_df = pd.DataFrame([report])
report_df.to_excel('monthly_report.xlsx', index=False)
print("Monthly report created!")
for key, value in report.items():
print(f"{key}: {value}")
Common Problems
Excel File is Too Large
# Load only required columns
df = pd.read_excel('large_file.xlsx', usecols=['Date', 'Revenue'])
# Or: Read only sample
df = pd.read_excel('large_file.xlsx', nrows=10000)
Missing Values
# Check for NaN values
print(df.isnull().sum())
# Remove or replace NaN
df_clean = df.dropna() # Remove rows with NaN
df['Revenue'].fillna(0, inplace=True) # Replace NaN with 0
Date Formats
# Parse date with format
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')
# Handle different date formats
df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
Conclusion
Pandas makes Excel analysis faster, repeatable, and scalable. Instead of complex formulas in Excel, write Python code once and simply re-run it with new data.
When to use Pandas instead of Excel?
- ✅ Large datasets (> 100,000 rows)
- ✅ Recurring analyses
- ✅ Complex groupings
- ✅ Automation (cronjobs, pipelines)
When Excel is sufficient?
- 📊 One-time, small analyses
- 📊 Visualizations for presentations
- 📊 Ad-hoc analysis without code
Further Resources: