Sub topic 9
Segmenting queries and pages to answer real questions
A site-wide line of clicks or average position hides most of what happens. A brand campaign can raise total clicks while non-brand traffic falls. A strong blog section can cancel out a weak product section. Segmentation splits the daily table into groups so that each trend answers one question.
This chapter assumes you have read the earlier chapters on the daily data model and on impression-weighted position. It also assumes you can read basic pandas code.
Start with the question, not the dimension
Pick the segment after you know what you need to decide. The table below shows common questions and the segment that answers each.
| Question | Segment | Why it helps |
|---|---|---|
| Are we growing beyond people who already know us? | Brand vs non-brand queries | Brand queries mostly reflect awareness, not SEO work. |
| Which part of the site is losing traffic? | Page groups (template or folder) | Pages built from one template tend to move together. |
| Did a mobile problem hit us? | Device | A mobile-only drop points to rendering or usability issues. |
| Is a regional market behaving differently? | Country | Seasonality and competitors differ by market. |
| Which topics deserve content investment? | Topic clusters of queries | Single queries are noisy, clusters are stable. |
Brand vs non-brand queries
Brand queries contain your company name, product names, or common misspellings of them. People who type them already want you. Their CTR is high and their position is usually 1 or 2. If you mix them with non-brand queries, you get two problems:
- Total CTR looks healthy even when non-brand CTR is poor.
- Average position looks better than the position people actually see for generic terms.
Build the classifier from a regular expression you maintain in one place. Include misspellings and the domain name without the extension.
Page groups
Pages rarely tell a story one at a time. Group them by something that explains behavior:
- URL folder, such as
/blog/,/products/,/docs/. - Template type, such as category page, product page, article.
- Business owner or funnel stage.
Folder rules are easy to automate, but they only work if URLs are consistent. Check the rules with a sample of URLs before you trust them. Use an ordered list of rules, put specific ones first, and add an explicit other bucket. If other grows past a few percent of clicks, your rules need work.
Putting both segments in code
The following script is self-contained. It labels each row with a query segment and a page group, then computes CTR and impression-weighted position per segment. It uses the same columns as the daily table from earlier chapters.
import re
from urllib.parse import urlparse
import pandas as pd
df = pd.DataFrame(
{
"date": pd.to_datetime(["2026-01-05"] * 6),
"query": [
"acme shoes", "acme", "running shoes",
"how to lace running shoes", "best trail shoes", "acm shoes",
],
"page": [
"https://example.com/products/shoes",
"https://example.com/",
"https://example.com/products/running",
"https://example.com/blog/lace-running-shoes",
"https://example.com/blog/best-trail-shoes",
"https://example.com/products/shoes",
],
"clicks": [120, 300, 15, 40, 22, 4],
"impressions": [400, 800, 1500, 2000, 1800, 20],
"position": [1.2, 1.1, 8.5, 5.4, 6.8, 1.9],
}
)
BRAND = re.compile(r"\bacme?\b|\bacm\b", re.IGNORECASE)
PAGE_RULES = [ # ordered: first match wins
("/blog/", "blog"),
("/products/", "products"),
]
def query_segment(query: str) -> str:
return "brand" if BRAND.search(query) else "non-brand"
def page_group(url: str) -> str:
path = urlparse(url).path
if path == "/":
return "home"
for prefix, name in PAGE_RULES:
if path.startswith(prefix):
return name
return "other"
df["query_segment"] = df["query"].map(query_segment)
df["page_group"] = df["page"].map(page_group)
df["pos_x_impr"] = df["position"] * df["impressions"]
def summarize(frame: pd.DataFrame, by: list[str]) -> pd.DataFrame:
out = frame.groupby(by, as_index=False)[
["clicks", "impressions", "pos_x_impr"]
].sum()
out["ctr"] = out["clicks"] / out["impressions"]
out["avg_position"] = out["pos_x_impr"] / out["impressions"]
return out.drop(columns="pos_x_impr")
print(summarize(df, ["query_segment"]))
print(summarize(df, ["query_segment", "page_group"]))Two details matter here. The script sums clicks, impressions and the position-times-impressions product first, and only then divides. This is the same rule as in the position chapter, applied at the segment level. The BRAND pattern also catches the misspelling acm, which a plain substring match on acme would miss.
Choosing the grain: adding device and country
Adding device or country to the API request multiplies the number of rows. A table with date, query and page may already hit the row limits for large sites. Adding two more dimensions makes it larger again. Choose one of these strategies:
- Collect a second, coarser table with
date,device,countryand no query or page. It is small, and it answers "did mobile drop?" quickly. - Keep the detailed table at
date,query,page, and adddeviceonly for sites small enough to afford it. - Pull country only for the few markets you actually serve.
Topic clusters of queries
Individual queries come and go, and many have very few impressions. A cluster, such as "running shoes", "best running shoes" and "running shoes for flat feet", is easier to read. Start with simple rules: a list of keywords and a regular expression per cluster. Avoid fancy language models until the simple rules stop working. Keep a mapping table (query, cluster) in your database so that new queries can be reviewed and added.
Watch for overlap. If one query matches two clusters, either pick the first match or give it a priority. Never count a query twice, or your cluster totals will exceed the real totals.
Common errors
- Averaging segment CTRs. CTR for the combined group is total clicks divided by total impressions, not the mean of per-row CTRs.
- Segments that change over time. If you edit the brand regex, recompute the whole history. Otherwise a trend line shows your rule change, not user behavior.
- Tiny segments. A segment with 30 impressions a week produces wild CTR and position values. Show the volume next to each ratio, or set a minimum impression threshold before charting.
- Comparing segments of different seasonality. Gift pages peak in winter, tax pages in spring. Compare each segment with its own prior year, as covered in the trend chapter.
- Treating position as comparable across devices. Mobile and desktop result pages differ, so the same query can have different positions on each. Segment by device before comparing positions.
A worked reading
Suppose total clicks fall 8% month over month. You split by query segment: brand clicks are flat, non-brand clicks are down 15%. You then split non-brand by page group: /blog/ is down 30% and /products/ is flat. Finally you check the blog's weighted position, which is stable, while its impressions dropped. Position held but impressions fell, so the likely cause is lower demand or a search result feature taking attention, not a ranking loss. Segmentation did not give the answer by itself, but it narrowed the investigation from "the site" to one folder and one metric.
Exercise
Your table has rows for a brand query (CTR 40%, 1,000 impressions) and a non-brand query (CTR 2%, 9,000 impressions). What is the combined CTR, and why is it wrong to report the average of 40% and 2%?
Show answer
Clicks are 400 + 180 = 580 over 10,000 impressions, so the combined CTR is 5.8%. The simple average of 40% and 2% is 21%, which ignores that 90% of impressions come from the low-CTR query. Ratios must be recomputed from summed clicks and impressions.
Exercise
You change your brand regular expression to include a new product name. What must you do with the stored history, and what happens if you skip it?
Show answer
Reclassify all historical rows with the new rule and recompute the segment tables. If you apply it only to new data, the brand segment appears to jump on the change date, and the non-brand segment appears to drop, even though user behavior did not change.