Keep KPI Cards Honest While a Live Dashboard Keeps Moving

Keep KPI Cards Honest While a Live Dashboard Keeps Moving
Suggested cover: a live operations dashboard with a top row of bold KPI cards above the main charts.

The KPI row reads better when the guard, layout and formulas are split apart

The summary section is still most useful when it stays direct, but the original block contains several different responsibilities at once: an empty-state branch, the column layout and four metric formulas. Breaking that into smaller literal slices makes the row easier to inspect without changing the code itself.

These fragments are still taken from the same render section of the dashboard. They are simply distributed across more blocks so each step is easier to place back into the page.

TermMeaningWhy it matters
Empty stateThe branch that handles a missing frame.It prevents the metrics row from pretending there is live data when there is not.
Metric layoutThe four-column structure above the charts.It defines the visual rhythm of the summary area.
Metric formulasThe expressions passed directly into each card.They make the summary logic easy to verify against the frame.

The render section continues with the guard branch

        if df.empty:
            st.warning("No data in database. Please run video processing first.")
        else:

The empty-state check now has its own block, which makes the fallback behavior easier to identify before the metrics begin.

The metric layout sits in a separate step

            col1, col2, col3, col4 = st.columns(4)

The column declaration becomes much easier to spot when it is not buried inside the formulas themselves.

The first half of the KPI row stays literal

            col1.metric("Total Vehicles", f"{df['intensity'].sum():,}")
            col2.metric("Average Speed", f"{df['avg_speed'].mean():.1f} px/sec")

The first two cards show the total and the average, and leaving them together keeps the pair easy to compare.

            col3.metric("Max Intensity", f"{df['intensity'].max():,}")
            col4.metric("Total Records", f"{len(df):,}")

The second pair finishes the row with peak intensity and row count, still using the original dataframe formulas.

  • The summary guard remains intact, but it now reads as its own step.
  • The layout line is separated from the formulas, which makes the top-row structure easier to restore.
  • The four metrics are distributed across two small code blocks instead of one long slab.
A KPI row feels easier to rebuild when its guard, layout and formulas are visible as separate source slices.