AnalystPath

Classify Category Nodes

PandasMediumMid level~10 min

Problem

A `Category` DataFrame stores a taxonomy as `node_id` and `parent_id`, where `parent_id` is the id of the node directly above it (the root has `parent_id` empty / NaN).

For each node, classify its role:

- `Top` — the node has no parent (root).
- `Branch` — the node has a parent and is itself the parent of at least one other node.
- `Leaf` — the node has a parent and no children.

Return columns `node_id` and `role`.

Input data

Example rows — the live problem includes the full dataset.

category
node_idparent_id
1
21
31
42
52

Expected output

Your answer should return 5 rows with the columns node_id, role.

Starter code (Pandas (Python))

import pandas as pd

def classify_nodes(category: pd.DataFrame) -> pd.DataFrame:
    # Your code here
    return category

Solve this Pandas question free

Write Pandas (Python) and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related Pandas questions