Sub topic 5
Grouping queries into exposed and comparison cohorts
This chapter assumes you can pull query-level rows from the Search Console API, as in the previous chapter. It also assumes you know pandas groupby operations and understand clicks, impressions, CTR and average position. You will build two groups of queries: one that shows an AI Overview on the results page, and one that does not. Later chapters compare CTR between those groups.
Why the unit is the query
An AI Overview appears for a specific search, not for a whole site. Two pages on your site can rank at position 3 for different queries, and only one of those results pages may show an overview. A site-wide before-and-after comparison mixes both situations, so the effect is diluted and seasonality can swamp it.
Grouping at the query level gives you a treated group and an untreated group measured over the same days. Anything that hits both groups equally, such as a holiday or a tracking change, cancels out in the comparison.
The group definitions below set up that comparison.
| Cohort | Definition | Role |
|---|---|---|
| Exposed | Queries where a SERP tracker saw an AI Overview in most checks before the change window | Treated group |
| Comparison | Queries tracked in the same period with no AI Overview in any check | Control group |
| Excluded | Mixed, untracked, brand, or low-volume queries | Left out to keep the groups clean |
The cohort-building workflow
The diagram shows the order of decisions. Exposure is decided from pre-period data only.
Defining exposure from the SERP tracker
Search Console does not tell you, query by query, whether an AI Overview appeared. You infer exposure from a rank or SERP tracking tool that records each checked query's results page on a schedule. Export those snapshots with one row per query per check and a boolean for whether an overview was present.
Use only snapshots taken before the change window. If you use snapshots from the window itself, you risk defining exposure by the outcome you want to measure.
Overview presence is not stable. A query can show one on Monday and not on Thursday, because Google varies when it generates them. Take the share of pre-period checks with an overview, then apply two thresholds:
- Exposed: the share is at least 0.5.
- Comparison: the share is exactly 0.
- Everything in between is ambiguous and is dropped.
The gap between the thresholds costs sample size, and it buys cleaner groups. If your comparison group sometimes shows an overview, the measured difference shrinks toward zero.
Choosing the comparison group
A comparison group is only useful if it would have behaved like the exposed group without the overviews. Check these properties on the pre-period data:
- Similar intent. Informational questions are far more likely to trigger overviews than transactional queries. If your exposed queries are all "what is" and your comparison queries are all "buy", their CTR may move differently for reasons unrelated to overviews. Compare within an intent type where you can.
- Similar position. CTR depends heavily on rank. Compare queries in similar position bands, for example 1 to 3 and 4 to 10.
- Enough volume. CTR on 20 impressions is noise. Set a minimum pre-period impression count.
- No brand queries. Brand searches behave differently, with high CTR that is driven by demand rather than by the results page. Filter them with a pattern.
Perfect matching is rarely possible. Aim for comparable groups, then report the pre-period differences instead of hiding them.
Building the cohorts in pandas
The script below is self-contained. It uses a small synthetic stand-in for both the API rows and the tracker export, so you can run it as shown. Swap in your real data by replacing the two data-construction blocks.
import re
import numpy as np
import pandas as pd
CHANGE = pd.Timestamp("2026-02-01")
BRAND = re.compile(r"example", re.I)
MIN_PRE_IMPRESSIONS = 100
# name: (AI Overview seen at each pre-period check, pre clicks, post clicks)
spec = {
"how to descale a kettle": ([True, True, True], 60, 38),
"what is limescale": ([True, True, False], 50, 34),
"best kettle for hard water": ([False, False, False], 45, 43),
"electric kettle sizes": ([False, False, False], 40, 39),
"kettle price": ([True, False, False], 30, 29),
"example kettle review": ([False, False, False], 80, 80),
"buy descaler online": ([], 25, 24), # never tracked
}
check_dates = ["2026-01-05", "2026-01-15", "2026-01-25"]
# Stand-in for the rows returned by the Search Console API
rows = []
for query, (_, pre_clicks, post_clicks) in spec.items():
for date, clicks in (("2026-01-10", pre_clicks), ("2026-02-10", post_clicks)):
rows.append({
"keys": [date, query, "/guides/page"],
"clicks": clicks,
"impressions": 1000,
"ctr": clicks / 1000,
"position": 3.0,
})
# Stand-in for the SERP tracker export: one row per query per check
tracker = pd.DataFrame(
[
{"query": q, "check_date": d, "ai_overview": flag}
for q, (flags, _, _) in spec.items()
for d, flag in zip(check_dates, flags)
]
)
tracker["check_date"] = pd.to_datetime(tracker["check_date"])
# Search Console rows -> flat table
df = pd.DataFrame(rows)
df[["date", "query", "page"]] = pd.DataFrame(df["keys"].tolist(), index=df.index)
df["date"] = pd.to_datetime(df["date"])
df["period"] = np.where(df["date"] >= CHANGE, "post", "pre")
# Eligibility: enough pre-period volume, not a brand query
pre_impr = df[df["period"] == "pre"].groupby("query")["impressions"].sum()
eligible = {
q for q in pre_impr[pre_impr >= MIN_PRE_IMPRESSIONS].index if not BRAND.search(q)
}
# Exposure share from pre-period tracker checks only
pre_checks = tracker[tracker["check_date"] < CHANGE]
share = pre_checks.groupby("query")["ai_overview"].mean()
exposed = set(share[share >= 0.5].index)
comparison = set(share[share == 0].index)
def assign(query):
if query not in eligible:
return None
if query in exposed:
return "exposed"
if query in comparison:
return "comparison"
return None # mixed or untracked
df["cohort"] = df["query"].map(assign)
df = df[df["cohort"].notna()]
print(df.groupby("cohort")["query"].nunique())
summary = df.groupby(["cohort", "period"])[["clicks", "impressions"]].sum()
summary["ctr"] = summary["clicks"] / summary["impressions"]
print(summary)Running it gives two exposed queries and two comparison queries. The exposed CTR falls from 0.055 to 0.036, and the comparison CTR falls from 0.0425 to 0.041. The summary table is the input to the difference-in-differences step in a later chapter.
What the code does differently from a naive version
A shorter version would label every query not in exposed_queries as "comparison". That quietly puts untracked queries, mixed queries and brand queries into the control group. Here, a query reaches the comparison cohort only if the tracker positively observed it without an overview. buy descaler online shows the difference: it has traffic but no tracker data, so it is excluded rather than assumed clean.
The script also computes CTR as total clicks divided by total impressions. Do not average the per-row ctr column. That gives each row equal weight regardless of volume and misstates the cohort CTR.
Pitfalls specific to cohorts
Selection on the outcome
Do not define the exposed cohort as "queries whose CTR dropped". That guarantees you find a drop, because you selected for it. Exposure must come from the tracker, and the CTR comparison comes afterward.
Search Console omits some queries
Search Console withholds anonymized queries, which are rare queries that too few people searched. Cohort totals therefore will not match the property-level total in the Performance report. The omission is usually similar in both cohorts, but check that the share of clicks you can see is comparable before and after. If it shifts, your cohorts are measured with different completeness.
Row limits and the page dimension
Requesting date, query and page together produces many rows, and the API returns at most 25,000 per request. Page through with startRow until a response returns fewer rows than you asked for. If you stop at the first page, you silently drop the long tail, and the tail is where cohorts are thinnest.
Contamination over time
Overviews expand to new queries. A query in your comparison group can start showing one during the post period. If your tracker keeps running, take a second snapshot after the window and check how many comparison queries became exposed. A few percent is tolerable. If many did, say so in your report, because the estimate then understates the true effect.
Regression to the mean
Queries chosen because they had unusually high CTR in the pre-period tend to fall back toward their average even with no change. If your cohorts differ greatly in pre-period CTR, compare them against that baseline instead of assuming they share the same starting point.
Checking balance before moving on
Before comparing post-period CTR, compare the cohorts on the pre-period only. Look at four things: query count, total impressions, impression-weighted average position, and CTR. Small differences are normal. Large differences, such as exposed queries averaging position 2 and comparison queries averaging position 9, mean CTR levels are not comparable. In that case, narrow both cohorts to a shared position band.
The next chapter reads CTR, impressions and position by cohort, using the groups built here.
Exercise
A colleague builds the comparison cohort as "every query in Search Console that is not in the exposed list". Give two kinds of query this wrongly includes, and say how the script in this chapter avoids each.
Show answer
It wrongly includes (1) queries the SERP tracker never checked, whose exposure is unknown, and (2) queries that showed an AI Overview in only some checks, which are partly exposed. Brand and low-volume queries also leak in. The script requires a comparison query to be tracked with zero overview sightings in the pre-period (share equal to 0), so untracked queries have no share and mixed queries fall between the 0 and 0.5 thresholds. Both are excluded, and brand and low-volume queries are removed by the eligibility filter.
Exercise
Why is it wrong to define the exposed cohort using snapshots taken after the change window begins, and why is averaging the per-row ctr column wrong for cohort CTR?
Show answer
Using snapshots from inside the window can tie exposure to the outcome, for example if overviews appear on queries whose clicks already fell, and it can mix treatment with the effect you are measuring. Averaging per-row ctr gives low-volume rows the same weight as high-volume rows. The correct cohort CTR is the sum of clicks divided by the sum of impressions.