What is the keepdims parameter in NumPy aggregations, and why is it useful?

Quick Overview

Asks what the keepdims argument does in NumPy reductions such as sum, mean and max, and why it is useful. Tests understanding of array shapes and broadcasting rules, and of the shape bugs that appear when a reduced axis is dropped.

What is the keepdims parameter in NumPy aggregations, and why is it useful?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What is the `keepdims` parameter in NumPy aggregations, and why is it useful? ```hint Compare shapes Write down the shape of `a.sum(axis=1)` for a (3, 4) array, then line it up against (3, 4) using the broadcasting rules, which compare shapes starting from the last axis. ``` ### What a Strong Answer Covers - What `keepdims=True` does to the shape of a reduction's result, shown with a concrete shape - Why the retained size-1 axis matters when broadcasting the result back against the original array - What goes wrong without it, including the case where the shapes broadcast anyway - Typical uses such as centering, per-axis normalization and softmax ### Follow-up Questions - Without `keepdims`, how else could you restore the reduced axis? - On a square (n, n) array, why is `x - x.mean(axis=1)` a silent bug? - How does `keepdims` behave with `axis=None` or a tuple of axes? - Write a numerically stable softmax over the last axis of a batch of logits.

Overview: Asks what the keepdims argument does in NumPy reductions such as sum, mean and max, and why it is useful. Tests understanding of array shapes and broadcasting rules, and of the shape bugs that appear when a reduced axis is dropped.

General logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What is the keepdims parameter in NumPy aggregations, and why is it useful?

What a Strong Answer Covers Guidance

  • What keepdims=True does to the shape of a reduction's result, shown with a concrete shape
  • Why the retained size-1 axis matters when broadcasting the result back against the original array
  • What goes wrong without it, including the case where the shapes broadcast anyway
  • Typical uses such as centering, per-axis normalization and softmax

Follow-up Questions Guidance

  • Without keepdims , how else could you restore the reduced axis?
  • On a square (n, n) array, why is x - x.mean(axis=1) a silent bug?
  • How does keepdims behave with axis=None or a tuple of axes?
  • Write a numerically stable softmax over the last axis of a batch of logits.