← Blog/KNN for Marketing: Fill In Missing CRM Data, Step by Step
Machine LearningKNNPythonData QualityMarketing Analytics
Machine Learning · 21 min read

KNN for Marketing: Fill In Missing CRM Data, Step by Step

Use k-nearest neighbours to estimate missing company headcount in a CRM: real Python code, an honest test against simple fills, and interactive charts.

· Martin Guzman

This is a business case for k-nearest neighbours (KNN): we use it to fill in company headcount where a CRM has none, step by step in Python. On companies whose real headcount we hid, KNN puts 88.6 percent in the right size band, against 64.0 percent for the usual fix of filling every blank with the median.

KNN estimates a missing value by finding the complete records that look most like the incomplete one and combining their values. This guide focuses on the business problem and the build. For the math behind the method, how to choose its settings and how to judge it, read How KNN Works first or alongside.

Every number, table and chart below is real output from code you can download and run. The company and its data are invented, so nothing here belongs to a client.

The application: a CRM with holes in it

Northpine Software is the made-up company whose data we use throughout this series. Its CRM holds 3,000 companies: prospects, customers and everything in between. For 706 of them, 23.5 percent, the employee count is blank.

That one blank field breaks more than it looks like:

  • Routing. Northpine sends small businesses (1 to 49 employees) to an inside sales team, mid-market companies (50 to 499) to account executives, and enterprises (500 and up) to a named-account team. A blank headcount means the lead sits in a queue or lands with the wrong team.
  • Segment sizing. "How many mid-market healthcare companies do we know?" has no honest answer while a quarter of the records cannot be placed.
  • Lead scoring. Company size is a common input to scoring models, including the lookalike list in this series. A model cannot score a company on a column that is empty.

What teams usually do

Without a model, teams do one of three things:

  • Leave it blank. The company drops out of every report and every rule that uses size.
  • Fill in the median. Every blank gets the typical headcount, so routing and reports work again. At Northpine that typical value is about 140 employees (the median of the known headcounts outside the test set in step 5), which puts every blank in mid-market.
  • Buy enrichment. A data vendor fills what it can. Vendors cover large companies well and small ones poorly, which is exactly why the remaining blanks lean small.

What KNN changes

KNN fills each blank from the companies that most resemble it, using what the CRM does know: revenue, LinkedIn followers, open job postings, office locations, company age, website size and industry. To find out how well that works, we hid 500 headcounts that we did know and asked each method to estimate them (step 8 shows the code):

How blanks are filledTypical errorWithin 1.5× of the truthSize band right
Overall median×2.2627.0%64.0%
Median of the company's industry×2.2827.4%64.0%
KNN, 10 nearest companies×1.3071.8%88.6%

"Typical error ×1.30" means the middle company's estimate is off by a factor of 1.30: a company of 100 people would be estimated at about 77 or 130. Measuring error as a factor rather than in employees is deliberate. Missing 40 people matters for a company of 60 and does not matter for a company of 4,000.

The median fill gets the band right 64.0 percent of the time only because most companies happen to be mid-market. It sends every small company and every enterprise to the wrong team. Filling by industry does not help, because every industry has small and large companies.

What the teams receive

The CRM gets two new fields, never an overwrite: the estimated headcount, and a flag saying it is an estimate. For example, the first three real blanks filled in step 11:

CompanyIndustryRevenue (millions)LinkedIn followersHeadcount on fileEstimate
NF-00004Professional services2.3320blank41 (small business)
NF-00014Healthcare17.0370blank62 (mid-market)
NF-00016Software13.7250blank58 (mid-market)

And how each team uses it:

TeamDecisionWhat they do with the estimate
Sales operationsWhich team gets a new leadRoute on the estimated band, and tell the rep it is an estimate
Marketing operationsWho is in each segmentCount estimated companies in segment reports, shown separately
AnalyticsWhat goes into a scoring modelUse the estimate plus the flag as an input, so the model can learn that estimates are less reliable
Data ownersWhich records to verify firstAsk reps or a vendor to confirm the estimates closest to a band edge

Other places the same idea works

The same fill works on any column that other columns predict:

  • Industry from website text features, job titles and company name patterns.
  • Revenue from headcount, industry and funding stage.
  • Customer age or household size in consumer data, from purchase behaviour.
  • Missing survey answers, filled from respondents who answered the other questions the same way.

KNN in one minute

To fill one blank, KNN measures how far the incomplete company is from every complete company across all the columns it has, takes the k closest, and combines their values. For a headcount we take the average of their logarithms, which is the geometric mean: for example, the ten neighbours in step 10, with 90 to 446 employees, give 146. On a scale where sizes run from 5 to more than 5,000, that keeps one large neighbour from dragging a small company's estimate up.

Two things follow, and both shape the build below: every column must be put on the same scale before distances mean anything, and the estimate can only be as good as the columns that describe the company. How KNN Works explains both with the math.

Try it: pick a company whose headcount was hidden, change how many neighbours vote, guess, then reveal the truth.

Fill a blank headcount from the nearest complete companies
Try it
Company, headcount hidden:
101001,0001001k10kLinkedIn followers (log scale)employees (log scale)median fill: 140estimate 188
10
NF-00856 · Software · revenue $68.2M · 2 open jobs
188 employees
The geometric mean of its 10 nearest complete companies, size band 50–499.
Pick a k, make your guess, then show the true headcount.
nearest complete companiesother companies (sample of 400)median filltrue headcount
Five of the 500 test companies, their headcount hidden. Neighbours are found on all 12 columns, so some sit away from the company on these two axes. The estimate is the geometric mean of their headcounts.

The chart draws LinkedIn followers against headcount, so the neighbours do not always look nearest here. They are found on all twelve columns that describe each company, and followers is only one of them. Notice how a single neighbour gives a jumpy estimate, and how 40 neighbours pull every company toward the middle.

The data: Northpine's company records

This guide uses one table, northpine_firmographics.csv: 3,000 companies in Northpine's CRM, with what is known about each one. Here are the first five rows:

company_idindustryemployeesrevenue (millions)LinkedIn followersjob postingsofficesagewebsite pages
NF-00001Education69034.74,0206323267
NF-00002Professional services11721.752022884
NF-00003Manufacturing5,262754.421,37018234388
NF-00004Professional servicesblank2.3320111295
NF-00005Retail462.7220014268

And what every column means:

ColumnWhat it is
company_idNorthpine's record ID
industryThe company's sector, one of six
employeesHeadcount. Blank for 706 companies
annual_revenue_musdAnnual revenue, millions of US dollars
linkedin_followersFollowers of the company's LinkedIn page
open_job_postingsJobs the company is advertising now
office_locationsNumber of offices
company_age_yearsYears since the company was founded
website_pagesPages on the company's website

Two things to notice before writing any code.

Every other column is complete. In Northpine's CRM, headcount is the only column with gaps; the six other numbers and the industry are filled for all 3,000 companies. KNN needs some complete columns to measure distance with.

The blanks are not random. Step 2 shows that companies with a blank headcount have fewer followers, less revenue and smaller websites than the rest. The blanks lean small. That matters twice: a single fill value is wrong for them in a predictable direction, and any check of the method has to look at whether the estimates for the blanks look like small companies.

Step by step in Python

The code uses pandas and scikit-learn, both free. Every block below is a cell in the downloadable notebook, and every output shown is what it printed.

Step 1: load the data

import numpy as np
import pandas as pd
from sklearn.impute import KNNImputer
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import StandardScaler
 
firms = pd.read_csv("northpine_firmographics.csv")
print(firms.shape)
firms.head()
(3000, 9)

Three thousand companies and nine columns.

Step 2: see what is missing, and who

missing = firms["employees"].isna()
print(f"missing headcount: {missing.sum():,} of {len(firms):,} companies ({missing.mean():.1%})")
 
firms.groupby(missing.map({False: "headcount known", True: "headcount missing"}))[
    ["linkedin_followers", "annual_revenue_musd", "open_job_postings", "website_pages"]].median()
missing headcount: 706 of 3,000 companies (23.5%)
 
                   linkedin_followers  annual_revenue_musd  open_job_postings  \
employees                                                                       
headcount known                1040.0                21.60                2.0   
headcount missing               440.0                 8.85                1.0   
 
                   website_pages  
employees                         
headcount known            117.0  
headcount missing           76.0

The table compares the medians of the companies with and without a headcount. The companies with a blank have 440 LinkedIn followers against 1,040, revenue of 8.85 million dollars against 21.60 million, and smaller websites. Whatever fills the blanks should therefore produce smaller companies than the ones on file. Keep that in mind for step 11.

Step 3: choose the columns

numeric = ["annual_revenue_musd", "linkedin_followers", "open_job_postings",
           "office_locations", "company_age_years", "website_pages"]
 
table = np.log1p(firms[numeric])                                  # sizes vary a thousandfold
table = table.join(pd.get_dummies(firms["industry"], dtype=float))   # one column per sector
table["log_employees"] = np.log10(firms["employees"].astype(float))  # the column to fill
features = table.columns.drop("log_employees")
print(len(features), "columns describe each company")
12 columns describe each company

Three decisions sit in those lines:

  • Every size column goes in as a logarithm. Revenue, followers and job postings run from a handful to tens of thousands. On a log scale, the step from 10 to 100 counts the same as the step from 1,000 to 10,000, which is how size really works. log1p adds one before the logarithm so that zero job postings stays defined.
  • Industry becomes six yes-or-no columns, one per sector, because distance needs numbers.
  • Headcount is stored as log_employees, base-10, so 10 becomes 1, 100 becomes 2 and 1,000 becomes 3. Averaging these and converting back gives the geometric mean.

Step 4: hide some answers we know

known = firms.index[~missing]
rng = np.random.default_rng(42)
test_rows = np.sort(rng.choice(known, size=500, replace=False))
tune_rows = np.sort(rng.choice(np.setdiff1d(known, test_rows), size=500, replace=False))
 
truth = firms.loc[test_rows, "employees"].astype(float)
tune_truth = firms.loc[tune_rows, "employees"].astype(float)
print(f"known: {len(known):,}   test: {len(test_rows)}   tuning: {len(tune_rows)}")
known: 2,294   test: 500   tuning: 500

We cannot measure accuracy on the 706 real blanks, because nobody knows the answer. So we take companies whose headcount we do know and pretend we do not. Five hundred are the test set: hidden, estimated, and only compared with the truth at the end. Another 500 are hidden separately to choose k in step 7. The test headcounts stay hidden during that step too, so the test companies never influence the choice. default_rng(42) fixes the random draw, so your numbers will match these.

One caution: these hidden companies are a random sample of the known ones, while the real blanks lean small. The test tells you how well the method works on companies like the ones on file. Step 11 checks the real blanks separately.

Step 5: set the bar with simple fills

def size_band(n):
    return pd.cut(n, [0, 49, 499, np.inf], labels=["1-49", "50-499", "500+"])
 
def score(estimate, truth):
    factor = np.maximum(estimate / truth, truth / estimate)   # 2.0 = off by double or half
    return {"typical_error_factor": round(factor.median(), 2),
            "within_1.5x": round((factor <= 1.5).mean(), 3),
            "band_correct": round((size_band(estimate) == size_band(truth)).mean(), 3)}
 
others = firms.loc[np.setdiff1d(known, test_rows)]
overall_median = pd.Series(others["employees"].median(), index=test_rows, dtype=float)
industry_median = firms.loc[test_rows, "industry"].map(
    others.groupby("industry")["employees"].median()).astype(float)
print(f"overall median: {overall_median.iloc[0]:.0f} employees")
 
pd.DataFrame({"Overall median": score(overall_median, truth),
              "Industry median": score(industry_median, truth)}).T
overall median: 140 employees
 
                 typical_error_factor  within_1.5x  band_correct
Overall median                   2.26        0.270          0.64
Industry median                  2.28        0.274          0.64

Before any model, measure what the simple fixes achieve, so there is something to beat. Three measures, all on the 500 test companies:

  • Typical error factor: for each company, the estimate divided by the truth or the truth divided by the estimate, whichever is larger, then the median of those. A factor of 2.26 means the middle company is off by more than double or half.
  • Within 1.5×: the share of estimates no more than 50 percent too high or a third too low.
  • Band right: the share placed in the right size band, which is what routing depends on.

The median of companies outside the test set is 140 employees. Filling every blank with it gets the band right 64.0 percent of the time and lands within 1.5× of the truth for 27.0 percent. The industry median is no better, 2.28 against 2.26, because headcount varies far more within an industry than between industries.

Step 6: build the fill

def knn_fill(table, hide, k):
    """Hide the headcounts in `hide`, then estimate every missing headcount from its k nearest companies."""
    work = table.copy()
    work.loc[hide, "log_employees"] = np.nan
    scaler = StandardScaler().fit(work)                  # learns each column's mean and spread, ignoring gaps
    filled = KNNImputer(n_neighbors=k).fit_transform(scaler.transform(work))
    filled = scaler.inverse_transform(filled)
    column = work.columns.get_loc("log_employees")
    return pd.Series(10 ** filled[:, column], index=table.index).round()

The function hides the chosen headcounts and lets scikit-learn's KNNImputer fill every blank in the column. It has three parts:

  • StandardScaler puts every column on the same scale, so one standard deviation of followers counts as much as one standard deviation of revenue. It ignores blanks when it learns each column's average and spread.
  • KNNImputer finds, for each blank, the k nearest companies that have a headcount, measuring distance on all the other columns, and averages their values.
  • inverse_transform and 10 ** turn the scaled logarithm back into employees.

Hiding the test headcounts inside the function matters. The scaler and the imputer never see the answers they are about to be graded on.

Step 7: choose k

results, error = [], {}
for k in [1, 3, 5, 10, 20, 40, 80]:
    estimate = knn_fill(table, np.r_[tune_rows, test_rows], k)[tune_rows]   # test headcounts stay hidden too
    error[k] = np.maximum(estimate / tune_truth, tune_truth / estimate).median()
    results.append({"k": k, **score(estimate, tune_truth)})
 
best_k = min(error, key=error.get)   # lowest unrounded typical error; a tie goes to the smaller k
print(f"best k: {best_k}, typical error factor {error[best_k]:.4f}")
pd.DataFrame(results)
best k: 10, typical error factor 1.3000
 
    k  typical_error_factor  within_1.5x  band_correct
0   1                  1.39        0.588         0.850
1   3                  1.30        0.674         0.874
2   5                  1.31        0.666         0.890
3  10                  1.30        0.694         0.890
4  20                  1.32        0.652         0.870
5  40                  1.34        0.642         0.842
6  80                  1.43        0.562         0.796

This tries each k on the 500 tuning companies, with the 500 test headcounts hidden as well, so they are neither graded nor used as neighbours. best_k is chosen on the unrounded error, because rounded to two decimals several values of k look tied.

Choosing k: estimate error for each number of neighbours
Try it
×1.20×1.30×1.40neighbours used (k)typical error13510204080
Filled dot: k = 10, the lowest typical error. Hover a point to read it.
500 companies with known headcount, hidden for tuning, with the 500 test headcounts hidden too. Real output from step 7.

What the curve says:

  • One neighbour is noisy. With k = 1 the estimate is whatever the single closest company happens to be. The typical error is a factor of 1.39 and the band is right 85.0 percent of the time.
  • Three to ten neighbours do best. k = 3 and k = 10 both show 1.30 and k = 5 shows 1.31. Unrounded, k = 10 is the lowest, so the code picks it; it also gets the band right most often, 89.0 percent, level with k = 5.
  • Many neighbours blur. At 80 neighbours the estimate drifts toward the middle of the whole table: the typical error rises to 1.43 and the band score falls to 79.6 percent.

That is the opposite of the lookalike case, where 120 neighbours worked best. There, the outcome was rare and each neighbour only voted yes or no, so a large vote was needed for a steady score. Here every neighbour contributes a full number, so a few close ones carry more information than many distant ones.

Step 8: test it once

knn_estimate = knn_fill(table, test_rows, best_k)[test_rows]
 
comparison = pd.DataFrame({"Overall median": score(overall_median, truth),
                           "Industry median": score(industry_median, truth),
                           f"KNN, k={best_k}": score(knn_estimate, truth)}).T
comparison
                 typical_error_factor  within_1.5x  band_correct
Overall median                   2.26        0.270         0.640
Industry median                  2.28        0.274         0.640
KNN, k=10                        1.30        0.718         0.886

On the 500 test companies, KNN with ten neighbours is typically off by a factor of 1.30, lands within 1.5× of the truth for 71.8 percent of companies and gets the size band right for 88.6 percent. The test result matches the tuning result of 1.30, so the choice of k did not just fit the tuning companies.

Switch between the methods to see where each one goes wrong:

Estimated against true headcount, 500 test companies
Try it
Typical error
×1.30
Within 1.5×
71.8%
Band right
88.6%
10101001001,0001,000true headcount (log scale)estimated headcount
On the diagonal = exact. Grey lines mark the 50 and 500 employee band edges. Hover a dot.
size band rightsize band wrong
Companies whose headcount was hidden and never used to tune the method. Real output from steps 8 and 12.

The median fill is a flat line: every company gets 140, so small companies are overestimated and large ones underestimated, and all the red dots sit on the two ends. KNN's dots follow the diagonal, with errors spread on both sides.

Step 9: is it good enough to route on?

The band is what sales operations acts on, so look at where the band errors go:

pd.crosstab(size_band(truth).rename("true band"),
            size_band(knn_estimate).rename("KNN estimate"))
KNN estimate  1-49  50-499  500+
true band                       
1-49            83      16     0
50-499          13     298     9
500+             0      19    62
Does the estimate land in the right size band?
Try it
estimated band →1–4950–499500+true 1–4983160true 50–499132989true 500+01962
443 of 500 in the right band (88.6%). Hover a cell.
The 500 test companies. Rows are the true band, columns the band of the estimate. Real output from step 9.

Reading it as a marketer:

  • 83 of the 99 small companies stay with the small business team. The median fill sends all 99 to mid-market.
  • 62 of the 81 enterprises reach the enterprise team. The median fill sends none of them there.
  • No small company was called an enterprise, and no enterprise was called small. Every KNN error is one band off. Estimates close to a band edge are the ones most likely to be on the wrong side of it, so those are the records worth confirming first.

Step 10: explain an estimate

Like the lookalike score, a KNN estimate can be explained by showing the companies it came from. Take the first company in the test set:

work = table.copy()
work.loc[test_rows, "log_employees"] = np.nan
scaled = pd.DataFrame(StandardScaler().fit_transform(work[features]),
                      index=work.index, columns=features)
donors = work.index[work["log_employees"].notna()]
finder = NearestNeighbors(n_neighbors=best_k).fit(scaled.loc[donors])
 
example = test_rows[0]
distance, index = finder.kneighbors(scaled.loc[[example]])
show = ["company_id", "industry", "employees", "annual_revenue_musd",
        "linkedin_followers", "open_job_postings"]
print(firms.loc[example, show].to_dict())
firms.loc[donors[index[0]], show].assign(distance=distance[0].round(2))
{'company_id': 'NF-00013', 'industry': 'Healthcare', 'employees': 199.0, 'annual_revenue_musd': 14.0, 'linkedin_followers': 3260, 'open_job_postings': 2}
company_idindustryemployeesrevenue (millions)LinkedIn followersjob postingsdistance
NF-02322Healthcare12416.296011.30
NF-02306Healthcare9016.72,25011.49
NF-00306Healthcare11527.083021.56
NF-01364Healthcare20240.31,63061.60
NF-01203Healthcare25558.76,83031.62
NF-00292Healthcare11422.31,14011.66
NF-00693Healthcare12120.21,19011.69
NF-00261Healthcare11915.360021.75
NF-02556Healthcare44625.66,19031.75
NF-01823Healthcare9226.41,18011.76
neighbour_sizes = firms.loc[donors[index[0]], "employees"].astype(float)
print(f"geometric mean of the {best_k} neighbours: {10 ** np.log10(neighbour_sizes).mean():.0f}")
print(f"KNN estimate: {knn_estimate[example]:.0f}   true headcount: {truth[example]:.0f}")
geometric mean of the 10 neighbours: 146
KNN estimate: 146   true headcount: 199

The estimate is exactly the geometric mean of the ten neighbours' headcounts, 146. The true headcount is 199, so this estimate is too low, but it lands in the right band, mid-market. The neighbours are all healthcare companies with one to six job postings; NF-00013 has more LinkedIn followers than eight of the ten, which hints that it is larger than most of them. That is the kind of check a person can make in seconds, and one a median fill can never offer.

Step 11: fill the real blanks

filled = knn_fill(table, [], best_k)
firms["employees_filled"] = firms["employees"].astype(float).fillna(filled).astype(int)
firms["employees_is_estimate"] = missing.astype(int)
firms.to_csv("firmographics_filled.csv", index=False)
 
pd.DataFrame({
    "measured": size_band(firms.loc[~missing, "employees_filled"]).value_counts(normalize=True).sort_index(),
    "estimated": size_band(firms.loc[missing, "employees_filled"]).value_counts(normalize=True).sort_index(),
}).round(3)
                  measured  estimated
employees_filled                     
1-49                 0.185      0.438
50-499               0.657      0.531
500+                 0.158      0.031

Now fill the 706 real blanks, with no headcounts hidden. Two columns go back to the CRM: employees_filled, the measured value where there is one and the estimate where there is not, and employees_is_estimate, a flag set to 1 for every filled value. The original employees column is left as it was.

The first three real blanks and their estimates:

firms.loc[missing, ["company_id", "industry", "annual_revenue_musd", "linkedin_followers",
                     "employees", "employees_filled"]].head(3)
company_idindustryrevenue (millions)LinkedIn followersemployeesemployees_filled
NF-00004Professional services2.3320blank41
NF-00014Healthcare17.0370blank62
NF-00016Software13.7250blank58

These are the rows the teams receive: the blank stays blank in employees, and the estimate sits beside it.

Then the check promised in step 2. Among measured companies, 18.5 percent have fewer than 50 employees. Among the filled ones, 43.8 percent do, and only 3.1 percent are estimated at 500 or more. That is what the gaps in step 2 predicted: the blanks lean small, and KNN, which looks at their followers, revenue and website, places them accordingly. A median fill would have called all 706 of them mid-market.

The 706 filled headcounts against the 2,294 measured ones
Try it
0%5%10%15%20%25%101001,000employees (log scale)share of group
Median measured headcount 142; median estimate 59. Hover a bin.
measured headcountKNN estimate for a blank
Share of each group per size bin. The blanks lean small, so their estimates should be smaller: 43.8% are estimated under 50 employees, against 18.5% of measured companies. Real output from step 11.

Step 12: how does KNN compare?

A fair guide should tell you how the method does against a model built for the job:

train = np.setdiff1d(known, test_rows)
regression = LinearRegression().fit(table.loc[train, features], table.loc[train, "log_employees"])
regression_estimate = pd.Series(10 ** regression.predict(table.loc[test_rows, features]),
                                index=test_rows).round()
 
comparison.loc["Linear regression"] = score(regression_estimate, truth)
comparison
                   typical_error_factor  within_1.5x  band_correct
Overall median                     2.26        0.270         0.640
Industry median                    2.28        0.274         0.640
KNN, k=10                          1.30        0.718         0.886
Linear regression                  1.23        0.826         0.902

Linear regression, the subject of part 2 of this series, does better on this data: typically off by a factor of 1.23 against 1.30, with the band right 90.2 percent of the time against 88.6. That is not surprising. In Northpine's data, the logarithm of headcount rises in a straight line with the logarithms of followers, revenue and website size, which is exactly the shape linear regression assumes. When one column follows the others that neatly, a fitted line uses all the data at once, while KNN averages a handful of neighbours.

You would still choose KNN in several situations:

  • Many columns have gaps, not one. KNNImputer fills every column of a table in one pass, using whatever each record has. A regression needs a separate model per column and complete inputs for each.
  • The relationship is not a straight line. If headcount relates to revenue differently in retail than in software, KNN follows that without being told.
  • You need to show your working. "These ten similar companies have 90 to 446 employees" is easier for a sales rep to accept than a formula.

Both beat the median fill by a wide margin, which is the comparison that matters most in practice.

Using the filled column

An estimate is only useful if everyone downstream knows it is one. Ways Northpine could use this one:

  • Route on the estimated band, and say so. The lead record shows "estimated 41 employees" and the rep confirms the size on the first call.
  • Verify the edges first. Estimates just above or below 50 or 500 employees are where band errors happen. Send those to a vendor lookup or a rep's quick check, and leave the rest.
  • Keep estimates out of headline counts. In segment reports, show measured and estimated companies separately, so a planning number never rests on a guess without anyone knowing.
  • Feed the flag to models. A scoring model that receives both the estimate and employees_is_estimate can learn how far to trust the estimate.
  • Refill monthly. Each new verified headcount becomes a neighbour for the next fill, so estimates improve as the CRM does.

Then measure it. Every time a rep or vendor confirms a headcount that was estimated, record both values. After a few months, that log tells you the real error on real blanks, which is the number the hidden-value test in this guide can only approximate.

Mistakes to avoid

  • Overwriting the original column. Once an estimate replaces a blank, nobody can tell measured from guessed, and the next fill uses guesses as neighbours. Always add a new column and a flag.
  • Measuring error in employees. Off by 40 is a disaster for a company of 30 and nothing for one of 3,000. Measure error as a factor, or by the band you act on.
  • Skipping scaling and logarithms. Without them, LinkedIn followers, which run into the tens of thousands, decide every distance on their own.
  • Testing on rows the method already saw. Hide known values before fitting anything, including the scaler, or the test flatters the method.
  • Assuming blanks are random. Here they lean small. Always compare what the filled values look like with what the measured ones look like, and expect a difference when the gaps have a pattern.
  • Filling from columns that are themselves guesses. If revenue was also estimated, the headcount estimate inherits its error. Fill from measured columns where you can.
  • Using too many neighbours. For a numeric fill, a few close companies beat many distant ones. Large k pulls every estimate toward the average, which is the median fill again.

KNN and the rest of the series

For when KNN is the right choice and when it is not, see How KNN Works.

MethodWhat it gives youStrengthWatch out for
KNN (this case)An estimate from similar recordsFills any column, explains itselfScaling, a few columns doing all the work
Linear regressionHow much one number moves anotherBest when the relationship is a straight lineNeeds complete inputs
Logistic regressionA probability for a yes or no outcomeAccurate, clear weights per columnStraight-line assumptions
Decision treeRules that split customers into groupsRules anyone can readUnstable, overfits if allowed
XGBoostStrong predictions from many treesUsually the most accurateNeeds extra tools to explain

Download the data and the notebook

Both files are free to use. The notebook runs every step of this guide in order and already contains the outputs shown above, so you can compare your results line by line.

To run it: install Python, then run pip install pandas scikit-learn jupyter, put both files in one folder, and open the notebook with Jupyter. Step 11 writes your own firmographics_filled.csv.

Want this on your own data?

If your CRM has gaps that are breaking routing, reports or scoring, get in touch and we can look at which fields can be filled reliably and which need a better source.