Your supplier chart is ready for the manager, until the same firm lands in several industry bars. The uncomfortable question is whether those bars describe its main business or everything it lists.
An industry match can be a secondary classification: naicsPrimaryOnly defaults to false.
A matching NAICS code doesn't establish that the industry is the firm's primary classification. Calling every match a specialist gives the chart a stronger claim than the records support.
What does an industry match actually mean?
For supplier discovery, matching any listed industry can be useful. For a chart about primary industry classification, you need a different membership rule.
We can make that distinction with Dataspryva's SBA lookup Actor. Keep the broader matching rule for the comparison, then examine primaryNaicsCode separately.
Example: this request selects the exact food-service contractor code and makes the broader membership rule explicit.
import os
import pandas as pd
import duckdb
from apify_client import ApifyClient
target_code = "722310"
run_input = {
"mode": "byNaicsCode",
"naicsCodes": [target_code],
"naicsPrimaryOnly": False,
"maxItems": 100,
}
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
"dataspryva/sba-certified-small-business-and-federal"
).call(run_input=run_input)
if run["status"] != "SUCCEEDED":
raise RuntimeError(f"Run ended with status {run['status']}")
items = list(client.dataset(run["defaultDatasetId"]).iterate_items())
This creates a cohort selected by an exact-code match. It doesn't create a census of that industry.
The input's cap limits emitted records. A chart built from the returned cohort therefore needs a cohort label, rather than an unqualified claim about all businesses.
Keep the record separate from the search
A record describes a business. A search setting describes why that business was eligible to enter your dataset.
Those belong beside each other in an analysis, but they aren't interchangeable. In particular, naicsPrimaryOnly, naicsSector and naicsPrefixFilter are inputs, not business attributes.
The relevant fields carry different kinds of evidence:
| Field | What it holds and how we type it | Missingness and the analytical trap |
|---|---|---|
entityId |
SBA entity identifier; retain the raw value and create a string identifier | Without a usable identifier, a row cannot safely contribute to a distinct-business denominator |
primaryNaicsCode |
Primary classification; normalise to a nullable string after checking its shape | An omitted or unusable value leaves primary membership unknown, rather than disproving it |
naicsCodes[] |
Listed NAICS collection; retain the original collection until its exported element structure is established | Missing collection data cannot establish that a firm has no additional classifications |
keywords[] |
Structured capability tags; retain as a collection rather than turning them into industry codes | Tags support capability matching, not a substitute primary industry classification |
Empty fields are omitted. That gives you a missing key, not a reliable explanation of why the information is absent.
The record description doesn't establish an exhaustive scalar type contract for every classification value. Our string and nullable-boolean types below are analytical choices, with the original records preserved in items.
An array changes the counting unit
The myth is that an industry bar counts businesses in mutually exclusive buckets.
The actual counting path can look like this:
business record
|
+-- primary classification --> primary-industry grouping
|
+-- listed classifications --> business-code relationships
|
+-- overlapping industry bars
Exploding naicsCodes[] changes the unit from businesses to business-code relationships. Counting the exploded rows answers a relationship question.
Counting distinct entityId within each code answers a business-membership question. Summing those distinct counts across codes can still count the same business repeatedly.
A cleaner chart isn't necessarily a more exclusive population. Sometimes it just has better colours.
There's another boundary at extraction time. naicsSector is a client-side refinement because the upstream API supports exact-code matching rather than sector-prefix searches. naicsPrefixFilter also runs client-side.
Those refinements narrow the records available from the initial search. They don't establish that every business under a sector prefix was retrieved, and their descriptions don't establish primary-only membership. For that question, use the explicit primary-code rule.
Type identifiers without repairing evidence
NAICS values are identifiers, so arithmetic coercion is the wrong starting point. A malformed classification should become an audit item, not a plausible-looking code.
This loader accepts strings and integers, trims surrounding whitespace, and leaves other representations unusable. It retains the raw columns separately.
def identifier_text(value):
if isinstance(value, str):
return value.strip() or pd.NA
if isinstance(value, int) and not isinstance(value, bool):
return str(value)
return pd.NA
raw = pd.DataFrame(items).reindex(
columns=["entityId", "primaryNaicsCode"]
)
entities = pd.DataFrame(index=raw.index)
entities["entityId"] = raw["entityId"].map(identifier_text).astype("string")
primary_text = raw["primaryNaicsCode"].map(identifier_text).astype("string")
primary_valid = primary_text.str.fullmatch(r"[0-9]{2,6}", na=False)
entities["primary_code"] = primary_text.where(primary_valid)
The shape check follows the accepted code length. It isn't validation against a NAICS reference catalogue.
It also deliberately refuses to interpret a label, a decimal representation or a compound value as a code. We'd rather leave a classification unresolved than quietly invent its meaning.
We haven't parsed the listed-code collection. The comparison can use exact-code search membership without guessing whether an exported array contains scalar codes or another structure.
That trade-off limits the bridge below to the selected code. It isn't a reconstruction of every classification attached to each firm.
Missing primary codes change the denominator
For the selected code, a usable primary value can establish either a primary match or a different primary classification.
An unusable primary value establishes neither.
Keep that distinction visible before calculating shares. This cell also separates absent keys from explicit nulls and checks whether the entity identifier supports the intended counting unit.
primary_present = pd.Series(
["primaryNaicsCode" in item for item in items],
index=raw.index,
dtype="boolean",
)
entities["primary_status"] = pd.Series(
"unusable", index=raw.index, dtype="string"
)
entities.loc[~primary_present, "primary_status"] = "omitted"
entities.loc[
primary_present & raw["primaryNaicsCode"].isna(),
"primary_status",
] = "null"
entities.loc[primary_valid, "primary_status"] = "usable"
missing_entity_ids = int(entities["entityId"].isna().sum())
identified = entities.loc[entities["entityId"].notna()].copy()
if identified["entityId"].duplicated().any():
raise ValueError("Resolve repeated entity IDs before counting businesses.")
primary_coverage = identified["primary_status"].value_counts()
missing_entity_ids reports rows excluded from entity-level counting. primary_coverage reports classification coverage among the remaining businesses.
The Actor de-duplicates by SBA entity ID within a run. The explicit check remains useful when you later combine overlapping extractions: silently keeping an arbitrary row could choose between conflicting primary classifications.
A primary-match percentage among usable classifications answers a narrower question than a percentage among all identified returned businesses.
Dropping missing classifications changes the denominator. Filling them with False changes the claim.
Make the comparison table defendable
The bridge below records a relationship between each identified business and the exact code used in the request.
Its any-listed membership comes from the search rule. Its primary-match flag comes from the record.
bridge = identified[["entityId", "primary_code"]].copy()
bridge["matched_code"] = target_code
bridge["any_listed_match"] = True
bridge["primary_match"] = bridge["primary_code"].eq(target_code)
bridge["membership"] = pd.Series(
"primary unknown", index=bridge.index, dtype="string"
)
bridge.loc[
bridge["primary_match"].fillna(False), "membership"
] = "primary match"
bridge.loc[
bridge["primary_match"].eq(False).fillna(False), "membership"
] = "secondary-only match"
“Secondary-only” here means the selected code matched the search while a usable primary code differs. It doesn't mean the business has no primary classification.
Use that membership column for mutually exclusive chart bars. Keep the broader any-listed count in the comparison table, where its overlapping meaning is explicit.
This query produces chart-ready membership counts and names both denominators used for shares.
connection = duckdb.connect()
connection.register("entity_code_bridge", bridge)
comparison = connection.sql("""
WITH counts AS (
SELECT
matched_code,
count(*) AS identified_returned_businesses,
count(*) FILTER (WHERE any_listed_match)
AS any_listed_code_matches,
count(*) FILTER (WHERE primary_match IS TRUE)
AS primary_matches,
count(*) FILTER (WHERE primary_match IS FALSE)
AS secondary_only_matches,
count(*) FILTER (WHERE primary_match IS NULL)
AS primary_unknown,
count(primary_match) AS businesses_with_usable_primary
FROM entity_code_bridge
GROUP BY matched_code
)
SELECT *,
primary_matches::DOUBLE
/ nullif(identified_returned_businesses, 0)
AS primary_share_of_identified_returned,
primary_matches::DOUBLE
/ nullif(businesses_with_usable_primary, 0)
AS primary_share_where_primary_usable
FROM counts
""").df()
chart_data = bridge.groupby("membership").size().rename("businesses")
connection.close()
The share using all identified returned businesses reports the fraction positively established as primary matches. It leaves unknown classifications inside the denominator.
The share using usable primary classifications excludes those unknowns. Neither number should travel into a slide without its denominator.
The label stops short of specialisation
The worked example uses SBA Certified Small Business & Federal Contractor Lookup, but the distinction applies to any supplier export with primary and additional industry classifications.
A primary classification supports an exclusive grouping more readily than a capability list. It doesn't measure the share of revenue earned in that industry, the depth of a firm's expertise or its available capacity.
If the manager wants a specialisation chart, those are still unanswered questions.
“Primarily classified in this industry” is defensible. “Industry specialist” asks the classification to do a job it wasn't hired for.
Drafted with AI assistance and reviewed for accuracy.
Top comments (0)