An n-gram, in a Google Ads context, is a word or short run of words that appears inside your search terms: "jobs", "near me" or "free template". Looking at search terms one by one hides patterns, because a wasteful word is usually spread across dozens of different searches, each too small to notice. Adding up cost and conversions by n-gram brings those patterns to the surface.

This post builds a small pandas script that does exactly that from a standard search terms report export. No API access is needed: just a CSV and about sixty lines of Python.

What you'll get

Two CSV files:

  • Waste candidates: n-grams with meaningful cost and no conversions. These are where negative keywords usually come from.
  • Expensive converters: n-grams that do convert, but at a much higher cost per conversion than the account average. These need a closer look rather than a block.

Export the data

In Google Ads, open Insights and reports → Search terms, pick a date range with enough data (90 days is a reasonable start for a small account), and download as CSV. Make sure the Clicks, Cost and Conversions columns are included.

Two things to know about this export. First, it normally starts with a title row and a date range row above the column headers, and ends with total rows. Second, it isn't complete: Google omits some low-volume search terms for privacy (Google Ads Help). The analysis is a strong sample, not a full record.

Setup

pip install pandas 

Step 1: Load and clean the export

import re from collections import defaultdict import numpy as np import pandas as pd df = pd.read_csv("search_terms.csv", skiprows=2) COLS = {"Search term": "term", "Clicks": "clicks", "Cost": "cost", "Conversions": "conv"} df = df.rename(columns=COLS)[list(COLS.values())] df = df[~df["term"].astype(str).str.startswith("Total")] for col in ["clicks", "cost", "conv"]: df[col] = pd.to_numeric( df[col].astype(str).str.replace(r"[^\d.\-]", "", regex=True), errors="coerce", ).fillna(0) 

Column names depend on your interface language and column settings, so check them against your file and adjust COLS. The regular expression strips thousands separators and currency symbols before converting to numbers.

Step 2: Split search terms into n-grams

def ngrams(text, n): words = re.findall(r"[a-z0-9']+", str(text).lower()) return {" ".join(words[i:i + n]) for i in range(len(words) - n + 1)} 

Returning a set means each n-gram counts once per search term, even if a word repeats. That keeps the totals honest.

Step 3: Aggregate cost and conversions

rows = [] for n in (1, 2, 3): agg = defaultdict(lambda: [0, 0.0, 0.0, 0.0]) for t in df.itertuples(index=False): for gram in ngrams(t.term, n): a = agg[gram] a[0] += 1 a[1] += t.clicks a[2] += t.cost a[3] += t.conv for gram, (terms, clicks, cost, conv) in agg.items(): rows.append({"ngram": gram, "n": n, "terms": terms, "clicks": clicks, "cost": round(cost, 2), "conv": conv}) grams = pd.DataFrame(rows) 

One important point: these totals overlap. The cost of "plumber jobs london" is counted under "plumber", "jobs", "plumber jobs" and so on. That's intended, because each row answers "how much did searches containing this n-gram cost?", but it means the rows don't add up to the account total.

Step 4: Protect the words you sell

Before looking for waste, remove n-grams made from your own core service words. Otherwise "plumber" may appear as a top waste candidate simply because it's in every search.

PROTECT = {"plumber", "plumbing", "boiler"} # your own service words def is_protected(gram): return any(word in PROTECT for word in gram.split()) grams = grams[~grams["ngram"].apply(is_protected)].copy() 

Step 5: Find waste candidates and expensive converters

MIN_COST = 20 # ignore n-grams that cost less than this waste = (grams[(grams["conv"] == 0) & (grams["cost"] >= MIN_COST)] .sort_values("cost", ascending=False)) account_cpa = df["cost"].sum() / max(df["conv"].sum(), 1) grams["cpa"] = grams["cost"] / grams["conv"].replace(0, np.nan) expensive = (grams[(grams["conv"] > 0) & (grams["cpa"] > 2 * account_cpa) & (grams["clicks"] >= 20)] .sort_values("cpa", ascending=False)) waste.to_csv("waste_candidates.csv", index=False) expensive.to_csv("expensive_converters.csv", index=False) print(waste.head(20).to_string(index=False)) 

MIN_COST and the click threshold stop the script from flagging n-grams with too little data to judge. Set them relative to your budget: for a small account, £20 may be meaningful; for a large one, it's noise.

Turning results into negative keywords

The output is a list of candidates, not decisions. For each waste candidate, open the search terms that contain it and ask whether any of them could ever be a customer. Then choose a negative match type deliberately:

  • A clear-cut single word such as "jobs" or "free" usually works as a broad negative.
  • A multi-word theme such as "how to fix" is often safer as a phrase negative.

Google's negative keywords don't match close variants (Google Ads Help), so if "job" is a waste candidate, add "jobs" too.

Checking a candidate before you exclude it

Before adding anything as a negative, look at the actual searches behind it. A small helper makes that quick:

def searches_containing(gram): mask = df["term"].apply(lambda t: gram in ngrams(t, len(gram.split()))) return df[mask].sort_values("cost", ascending=False) print(searches_containing("course").head(15).to_string(index=False)) 

Read the list with one question in mind: could any of these people become a customer? If "course" appears in "first aid course for staff" and you sell staff training, the n-gram isn't waste at all. It just hasn't converted yet. If every search is "free online course" or "course near me for beginners" and you sell something else entirely, it's a safe exclusion.

This step is where most of the judgement happens. The script finds the patterns; a person who knows the business decides what they mean.

Reading the expensive converters

These are n-grams that do produce conversions, but at more than twice the account's average cost per conversion. Blocking them would be a mistake. Better questions are whether the landing page matches what those searchers want, whether the ad speaks to them, or whether the conversions themselves are valuable enough to justify the cost.

Choosing sensible thresholds

There's no universal setting for MIN_COST or the click threshold. A practical rule is to start with roughly the amount you'd normally pay for one conversion. If a word has cost that much and produced nothing, it deserves a look. If it has cost far less, there isn't yet enough evidence either way, and excluding it would be guesswork.

For the expensive converters, the "twice the account average" rule is deliberately loose. Some services are simply worth more, and a higher cost per conversion can be perfectly profitable. Use the list as a prompt for questions, not a verdict.

Sharing the results

The output CSVs are useful beyond the person running the script. A short summary for colleagues, such as "searches containing 'jobs' cost £180 last quarter and produced nothing, so we've excluded them", turns an abstract optimisation into something everyone can follow. It also makes it easier to spot when an exclusion clashes with something the business has started selling.

Limits worth knowing

  • Conversion lag. Recent clicks may convert later. Leave the last week or two out of your date range if your sales cycle is long.
  • Hidden searches. Privacy thresholds mean some spend sits in searches you can't see.
  • Small numbers. An n-gram with three clicks and no conversions tells you very little. Keep the thresholds sensible.
  • Words, not meaning. "Cheap" might be waste for one business and a buying signal for another. The script can't know which.

Making it a routine

Run the script monthly, or weekly for new campaigns. Save the outputs with the date in the file name, and keep a short note of which candidates you excluded and why. After a few months, you'll have a record of decisions that makes the next review much faster.

Where this fits

N-gram analysis is one part of keyword work: it refines a list after launch. Choosing the right keywords in the first place is the bigger lever, and this is a good companion read for that: a practical guide to choosing Google Ads keywords that convert.

Run the script on your last 90 days, read the top ten waste candidates, and you'll probably find at least one theme worth excluding today.

This article was drafted with AI assistance and reviewed by the Prox Digital Agency team. Test the code in your own environment before relying on it.