Learn / Programming / Pandas / Dates, Plots and Exporting

Intermediate 15 min

Dates, Plots and Exporting

Work with time series, make quick charts and save results.

What you will learn

  • Parse dates
  • Resample by period
  • Plot and export

Business data is full of dates: sales per day, signups per week, server load per minute. pandas has first-class time support, and quick plotting turns numbers into pictures you can share.

import pandas as pd
import numpy as np

rng = pd.date_range("2026-01-01", periods=90, freq="D")
sales = pd.DataFrame({"revenue": np.random.default_rng(1).integers(100, 500, size=90)}, index=rng)

sales.index.dayofweek        # 0=Monday ... 6=Sunday
sales.index.month
sales.loc["2026-02"]         # partial-string selection: all of February
sales.loc["2026-01-15":"2026-01-20"]

Resampling

resample is groupby for time: regroup daily data into weeks or months.

weekly = sales["revenue"].resample("W").sum()
monthly = sales["revenue"].resample("MS").agg(["sum", "mean"])
print(monthly)
sales["7d_avg"] = sales["revenue"].rolling(7).mean()      # smooth out noise
sales["pct_change"] = sales["revenue"].pct_change()
sales["cumulative"] = sales["revenue"].cumsum()
sales["lag_1"] = sales["revenue"].shift(1)                # yesterday's value
df = pd.read_csv("orders.csv", parse_dates=["created"])
df["created"] = pd.to_datetime(df["created"], format="%d/%m/%Y")   # be explicit for ambiguous formats
df["weekday"] = df["created"].dt.day_name()
df["days_since"] = (pd.Timestamp.today() - df["created"]).dt.days

Store timestamps in UTC and convert for display with tz_localize and tz_convert when time zones matter.

pip install matplotlib
import matplotlib.pyplot as plt

ax = sales[["revenue", "7d_avg"]].plot(figsize=(9, 4), title="Daily revenue")
ax.set_ylabel("USD")
plt.tight_layout()
plt.savefig("revenue.png", dpi=150)

sales["revenue"].plot.hist(bins=15)                    # distribution
employees.groupby("country")["salary"].mean().plot.bar()   # category comparison
  • Line charts for trends over time; bar charts for comparing categories; histograms for distributions; scatter plots for relationships.
  • Always label axes and add a title. Start bar charts at zero.
monthly.to_csv("monthly.csv")
monthly.to_excel("monthly.xlsx")
df.to_parquet("orders.parquet")     # compact and fast for big data
df.to_sql("orders", engine, if_exists="replace", index=False)
Big files

For data that does not fit in memory, read in chunks (chunksize=), keep only the columns you need (usecols=), or move to Polars or DuckDB.

Try it yourself

Create 60 days of random data, compute a 7-day rolling mean and the best week, and save a line chart to a PNG file.

Show solution
idx = pd.date_range("2026-01-01", periods=60)
s = pd.Series(np.random.default_rng(0).normal(100, 15, 60), index=idx)
print(s.resample("W").sum().idxmax())
ax = pd.DataFrame({"value": s, "7d": s.rolling(7).mean()}).plot(title="Demo")
ax.figure.savefig("demo.png")