Sub topic 11
Exporting reports and reproducing the gap in a script
This chapter assumes you have already run a gap report in Semrush or Ahrefs and know the categories from the earlier chapters: missing, weak, shared, strong. You should be comfortable with CSV files. The scripting part uses Python 3 and pandas, but the export advice applies even if you only use a spreadsheet.
Why export and rebuild the gap yourself
The built-in gap views are good for exploring. They fall short when you need to do any of these:
- Compare more domains than the tool allows in one report.
- Apply your own rule, such as "at least two competitors rank, and I do not".
- Keep a dated snapshot so you can compare against it after publishing.
- Combine data from both tools, or add your own columns such as intent or target page.
- Audit the tool's output by checking that its categories match the rule you think it applies.
Rebuilding the gap from per-domain exports gives you a rule you can read, version, and rerun. It also shows you where your logic and the tool's differ, which is useful. The tool's own definition of "missing" (for example, whether it needs all competitors or at least one to rank) is in its help pages. If your script's counts differ from a tab's counts, the definitions are the first thing to check.
Exporting the right data
Export one file per domain rather than one merged gap file. Per-domain files have the same shape, which makes merging simple. In either tool, open the organic keywords report for the domain (Semrush: Organic Research, Positions; Ahrefs: Site Explorer, Organic keywords) and export it.
Before you export, check these settings. A mismatch in any of them will quietly corrupt the comparison.
| Setting | What to keep identical across files | What goes wrong if it differs |
|---|---|---|
| Country or database | Same country for all domains | Rankings and volumes refer to different markets, so keywords look missing when they are not |
| Scope | Same domain, subdomain, or path mode (for example, root domain for all) | A competitor's blog subdomain may be excluded in one file and included in another |
| Device | Same device, desktop or mobile | Positions and volumes differ by device |
| Date | Exports taken on the same day | Rankings drift, which makes weak keywords look like moves |
| Filters | Same filters, ideally none | A volume filter on one file removes keywords the others still contain |
Export without filters and filter in the script. That way your rules are written down and you can change them without re-exporting.
Both tools cap exports by plan and by row limit, so a large competitor may be truncated. If the export is capped, sort by traffic or volume before exporting so the cutoff removes the least valuable rows. Note the truncation in your analysis notes.
Column names and file formats
The two tools name columns differently, and the file format can differ too.
| Meaning | Semrush header (typical) | Ahrefs header (typical) |
|---|---|---|
| Keyword text | Keyword | Keyword |
| Search volume | Volume | Volume |
| Keyword difficulty | Keyword Difficulty | KD |
| Ranking position | Position | Current position |
These headers change over time, so open each file and confirm them. Also check the encoding and delimiter. Some Ahrefs exports are UTF-16 with tab separators, which makes pd.read_csv fail or return one garbled column. If that happens, pass encoding="utf-16" and sep="\t". You can also open the file in a spreadsheet and re-save it as UTF-8 CSV.
The script
The script below loads three exports, normalizes them, builds one row per keyword, and separates missing keywords from weak ones. It adds a rename step so it works with either tool's headers. Save your exports as mine.csv, competitor_a.csv, and competitor_b.csv.
import pandas as pd
COLUMNS = ["Keyword", "Volume", "KD", "Position"]
COMPETITORS = ["a", "b"]
RENAME = {"Keyword Difficulty": "KD", "Current position": "Position"}
def load(path, site, **read_kwargs):
# Pass encoding="utf-16", sep="\t" here if your export needs it.
df = pd.read_csv(path, **read_kwargs).rename(columns=RENAME)[COLUMNS]
df["Keyword"] = df["Keyword"].str.lower().str.strip()
for col in ["Volume", "KD", "Position"]:
df[col] = pd.to_numeric(df[col], errors="coerce")
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)
ranked = missing.sort_values("score", ascending=False)
print(ranked.head(25))
ranked.to_csv("missing_keywords.csv")
weak.sort_values("Volume", ascending=False).to_csv("weak_keywords.csv")How it works
Normalization. Lowercasing and stripping whitespace make "Running Shoes " and "running shoes" the same key. Without this, the same keyword appears as missing for you and present for a competitor. drop_duplicates("Keyword") guarantees one row per keyword and site, which pivot requires. If duplicates remained, pivot would raise a "duplicate entries" error.
Coercion. pd.to_numeric(..., errors="coerce") turns placeholders such as "n/a" into NaN instead of failing. Note what this means for positions: a NaN position means "no data", and the script treats it the same as "does not rank".
The pivot. After pivot, each keyword is a row and columns me, a, b hold ranking positions. A missing value means that site has no ranking for that keyword in the export. This is the core of the whole gap: a gap is a pattern of empty cells.
Volume and difficulty. These belong to the keyword, not the site, but each export carries its own copy. Taking max across files smooths small differences between exports. Because all files come from the same tool and date, the values should usually agree.
Missing versus weak. The rule for missing says you have no position and n_competitors >= 2. For weak, min across competitor columns gives the best competitor position. A lower number is a better rank, so min(...) < me means at least one competitor outranks you. Comparisons with NaN evaluate to false, so a keyword where no competitor ranks is never marked weak.
The score. Volume / (KD + 1) rewards volume and penalizes difficulty. The + 1 avoids division by zero when KD is 0. It is a starting heuristic, not a measure of value. The prioritization chapter covers better scoring.
Checking the script against the tool
Run a reconciliation before trusting the output.
- Count the rows in
missingand compare with the tool's missing tab for the same domains. Expect differences if the tool's rule is not "at least two competitors". Changen_competitors >= 2to>= 1or to== len(COMPETITORS)and see which one matches. - Pick five keywords from your list and look each up in the tool. Confirm that the volume, KD, and positions match your table.
- Check that no keyword appears twice in the index:
assert gap.index.is_unique. - Check the null counts per column with
gap.isna().sum(). A column that is allNaNusually means a rename failed or a file was empty.
Common errors
KeyError: 'KD'. The header in your export differs from the names inRENAME. Printdf.columnsright after reading and extend the mapping.- One giant column in the DataFrame. The delimiter or encoding is wrong. See the format note above.
ValueError: Index contains duplicate entries. Duplicate keywords for one site survived. Make suredrop_duplicatesruns insideload.- Everything looks missing. The
mefile may be for a different country, or the keywords differ in case or spacing. Compare a few keywords from both files by eye. - Scores dominated by branded terms. Competitor brand names have high volume and low relevance to you. Filter them out before scoring, for example with
~gap.index.str.contains("brandname").
Keeping snapshots
Name output files with the export date, such as missing_keywords_2026-11-27.csv, and keep the raw exports with them. When you measure results later, you need the same inputs to compare against. If you change the rule or the score, record that in a comment at the top of the script, so a later difference in results can be traced to a change in logic rather than a change in the market.
Exercise
Your script reports 4,000 missing keywords, but the Semrush missing tab shows 900 for the same three domains. Give two likely causes and one check for each.
Show answer
First, the rules differ. Your script requires at least two competitors, while the tab may require that all competitors rank, or only one. Check by changing the threshold in the script (>= 1, >= 2, or all competitors) and seeing which count approaches 900. Second, the exports differ in settings such as country, device, or subdomain scope, or one was filtered or truncated by the row cap. Check by comparing the settings and row counts of the three files and re-exporting them with identical settings and no filters.
Exercise
Why does the script use drop_duplicates("Keyword") inside load rather than once on the combined table?
Show answer
The combined table legitimately holds the same keyword once per site. Deduplicating after concatenation would delete a keyword's rows for the other sites. Deduplicating inside load guarantees one row per keyword and site, which is what pivot needs.