Sub topic 11
Exporting reports and reproducing the gap in a script
The Semrush Keyword Gap and Ahrefs Content Gap screens are fine for exploring. They fall short when you want a repeatable process, a custom score, or a comparison across more domains than the interface allows. This chapter exports the raw data and rebuilds the gap logic in Python.
This chapter assumes you know the gap categories (missing, weak, shared, strong), the core metrics, and basic pandas: reading a CSV, filtering rows, and joining tables.
Export the right data
Export one organic keywords report per domain, not the combined gap view. Use the same country database for every file. Different databases give different volumes and positions, and mixing them produces a gap that does not exist.
Save the files as mine.csv, competitor_a.csv, and competitor_b.csv. Then check the headers. Semrush and Ahrefs name the same columns differently, for example "Search Volume" versus "Volume" and "Current position" versus "Position". Rename them to a common set before you merge.
The merge logic
The script has four steps:
- Load each file, lowercase and strip the keywords, and drop duplicates.
- Stack the three tables into one long table with a
sitecolumn. - Pivot to one row per keyword with one position column per site.
- Classify rows and score them.
import pandas as pd
# Each CSV is an organic keywords export for one domain, with the same
# country/database. Rename columns first if your export uses different headers.
COLUMNS = ["Keyword", "Volume", "KD", "Position"]
COMPETITORS = ["a", "b"]
def load(path, site):
df = pd.read_csv(path, usecols=COLUMNS)
df["Keyword"] = df["Keyword"].str.lower().str.strip()
df["site"] = site
return df.drop_duplicates("Keyword")
long = pd.concat([
load("mine.csv", "me"),
load("competitor_a.csv", "a"),
load("competitor_b.csv", "b"),
])
# One row per keyword, one column of positions per site.
gap = long.pivot(index="Keyword", columns="site", values="Position")
gap = gap.join(long.groupby("Keyword")[["Volume", "KD"]].max())
gap["n_competitors"] = gap[COMPETITORS].notna().sum(axis=1)
# Missing: you do not rank, at least two competitors do.
missing = gap[gap["me"].isna() & (gap["n_competitors"] >= 2)].copy()
# Weak: you rank, but below at least one competitor.
weak = gap[gap["me"].notna() & (gap[COMPETITORS].min(axis=1) < gap["me"])].copy()
# Simple opportunity score: more volume and lower difficulty rank higher.
missing["score"] = missing["Volume"] / (missing["KD"] + 1)
print(missing.sort_values("score", ascending=False).head(25))
print(len(weak), "weak keywords")Why each step matters
- Normalizing keywords. Without lowercasing and stripping, "Running Shoes " and "running shoes" count as different keywords, and you get false gaps.
- Dropping duplicates per site.
pivotraises an error if a keyword appears twice for one site. Deduplicating insideloadprevents that. - Taking the maximum volume and difficulty. The same keyword can carry slightly different values in each export. Taking the maximum gives one consistent row. Taking the mean also works, as long as you use the same rule every time.
- Requiring two competitors. A keyword that only one competitor ranks for may reflect that competitor's niche, not a real market gap. The threshold is a setting you can change.
- Scoring with
KD + 1. Adding one avoids division by zero for keywords with a difficulty of 0.
Position is a rank, so a lower number is better. In the weak filter, min(...) < me means at least one competitor ranks higher than you.
Check the script against the tool
Run the script, then open the same domains in the Keyword Gap or Content Gap interface. The missing counts should be close. Small differences usually come from your n_competitors threshold or from different filters. A large difference usually means mismatched country databases or a column that was renamed incorrectly.
Exercise
Why does the script require at least two competitors for a keyword to count as missing, and which line would you change to loosen that rule?
Show answer
A keyword ranked by only one competitor may reflect that competitor's niche rather than a real market gap, so requiring two adds confidence. To loosen the rule, change the threshold in gap["n_competitors"] >= 2 to >= 1.