Detect Table Grain via Candidate Keys in pandas

Quick Overview

Write a pandas function that finds every candidate key of one or two columns in a DataFrame, excluding columns with nulls and pairs that contain a single-column key. It tests uniqueness checks, minimality pruning, and returning a typed result frame in a fixed sort order.

Detect Table Grain via Candidate Keys in pandas

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Write `def key_candidates(df: pd.DataFrame) -> pd.DataFrame` that finds candidate keys of size 1 and 2 only. A set of columns is a key when it has no nulls in any member column and `df[cols].duplicated().sum() == 0`. The result tells you the grain of the table: which column, or which pair of columns, identifies one row. Requirements: - Test every single column and every pair. Skip any pair containing a size-1 key. - The output has exactly the columns `['key', 'n_columns', 'nunique_combos']`. - `key` (object) holds the member names sorted alphabetically and comma-joined, for example `'customer_id,order_date'`. `n_columns` (int64) is 1 or 2. `nunique_combos` (int64) is the number of distinct combinations, which equals `len(df)` for a true key. - Sort by `n_columns` then `key` ascending, then `reset_index(drop=True)`. - If no key of size 2 or less exists, return an empty frame with those columns and dtypes. On a 12-row frame where no single column is unique and exactly one pair is a key, the call returns one row: ```python key_candidates(df) # key n_columns nunique_combos # 0 customer_id,order_date 2 12 ``` A smaller frame you can check by hand: ```python df = pd.DataFrame({ 'order_id': [101, 102, 103, 104], 'customer_id': [1, 1, 2, 2], 'order_date': ['2024-01-01', '2024-01-02', '2024-01-01', '2024-01-02'], 'amount': [10, 10, 10, 20], 'promo_code': ['A', 'B', None, 'C'], }) key_candidates(df) # key n_columns nunique_combos # 0 order_id 1 4 # 1 customer_id,order_date 2 4 ``` `order_id` is unique on its own, so no pair containing it is reported. `promo_code` has four distinct values, but its null disqualifies it and every pair it belongs to. ```hint Nulls and duplicated() `duplicated()` treats NaN values as equal to each other, so a column with one null and otherwise distinct values passes the duplicate test. Apply the null rule as its own check. ``` ```hint Dtypes of an empty result `pd.DataFrame(columns=[...])` gives object columns. Think about how to build the result so the empty case still has int64 counts. ``` ### Constraints & Assumptions - Column names are unique strings. - A null is any value `isna()` flags (`None`, `NaN`, `NaT`). - Only keys of size 1 and 2 are searched. ### What a Strong Answer Covers - Applying the null rule separately from the duplicate check, and testing single columns before pairs. - Enforcing minimality by skipping every pair that contains a single-column key. - Building the `key` string in alphabetical member order and sorting the output deterministically. - Returning the same dtypes (object, int64, int64) whether or not any key is found. - The cost in terms of rows and columns, and edge cases such as a frame with zero rows or with fully duplicated rows. ### Follow-up Questions - How would you extend this to candidate keys of size 3 or more? - On a very wide table this is quadratic in the number of columns and rescans the rows for every pair. How would you speed it up? - Why is a strict uniqueness check risky on real-world data, and what would you report instead?

Overview: Write a pandas function that finds every candidate key of one or two columns in a DataFrame, excluding columns with nulls and pairs that contain a single-column key. It tests uniqueness checks, minimality pruning, and returning a typed result frame in a fixed sort order.

Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Write def key_candidates(df: pd.DataFrame) -> pd.DataFrame that finds candidate keys of size 1 and 2 only. A set of columns is a key when it has no nulls in any member column and df[cols].duplicated().sum() == 0. The result tells you the grain of the table: which column, or which pair of columns, identifies one row.

Requirements:

  • Test every single column and every pair. Skip any pair containing a size-1 key.
  • The output has exactly the columns ['key', 'n_columns', 'nunique_combos'] .
  • key (object) holds the member names sorted alphabetically and comma-joined, for example 'customer_id,order_date' . n_columns (int64) is 1 or 2. nunique_combos (int64) is the number of distinct combinations, which equals len(df) for a true key.
  • Sort by n_columns then key ascending, then reset_index(drop=True) .
  • If no key of size 2 or less exists, return an empty frame with those columns and dtypes.

On a 12-row frame where no single column is unique and exactly one pair is a key, the call returns one row:

key_candidates(df)
#                       key  n_columns  nunique_combos
# 0  customer_id,order_date          2              12

A smaller frame you can check by hand:

df = pd.DataFrame({
    'order_id':    [101, 102, 103, 104],
    'customer_id': [1, 1, 2, 2],
    'order_date':  ['2024-01-01', '2024-01-02', '2024-01-01', '2024-01-02'],
    'amount':      [10, 10, 10, 20],
    'promo_code':  ['A', 'B', None, 'C'],
})
key_candidates(df)
#                       key  n_columns  nunique_combos
# 0                order_id          1               4
# 1  customer_id,order_date          2               4

order_id is unique on its own, so no pair containing it is reported. promo_code has four distinct values, but its null disqualifies it and every pair it belongs to.

Constraints & Assumptions

  • Column names are unique strings.
  • A null is any value isna() flags ( None , NaN , NaT ).
  • Only keys of size 1 and 2 are searched.

What a Strong Answer Covers Guidance

  • Applying the null rule separately from the duplicate check, and testing single columns before pairs.
  • Enforcing minimality by skipping every pair that contains a single-column key.
  • Building the key string in alphabetical member order and sorting the output deterministically.
  • Returning the same dtypes (object, int64, int64) whether or not any key is found.
  • The cost in terms of rows and columns, and edge cases such as a frame with zero rows or with fully duplicated rows.

Follow-up Questions Guidance

  • How would you extend this to candidate keys of size 3 or more?
  • On a very wide table this is quadratic in the number of columns and rescans the rows for every pair. How would you speed it up?
  • Why is a strict uniqueness check risky on real-world data, and what would you report instead?