Learn / Programming / Pandas / Dates, Plots and Exporting

Pandas · Lesson 4 of 4

Dates, Plots and Exporting

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

  • Intermediate
  • 15 min read
  • 3 objectives

Before this lessonLesson 3: Grouping, Merging and Pivots

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.

Dates as a datetime index

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)

Rolling windows and change

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

Parsing dates from files

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.

Quick plots

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.

Exporting

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)
# Write your solution here
Course completeYou finished PandasReview the full course or pick your next one.