Compute the Mean of Each Row of a 2-D NumPy Array

Quick Overview

Compute the mean of every row of a 2-D NumPy array with a single vectorized reduction. It tests how the axis argument shapes the result and how you handle empty input, 1-D input and missing values.

Compute the Mean of Each Row of a 2-D NumPy Array

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Given a 2-D NumPy array of shape `(m, n)`, return a 1-D array of shape `(m,)` holding the mean of each row. Use a vectorized NumPy reduction, with no Python loop over the rows. The input is a valid non-empty 2-D array. Example: ```python import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) row_means(a) # -> array([2., 5.]) ``` ```hint Compare the shapes Put the input shape `(m, n)` next to the output shape `(m,)` and ask which axis the reduction has to remove. ``` ### What a Strong Answer Covers - Which axis the reduction runs along, and why that leaves one value per row - A vectorized call with no Python loop - The output shape and dtype, including for integer input - Time and space cost for an m×n array - How the function behaves on inputs outside the stated contract ### Follow-up Questions - How would you handle a possibly empty array or 1-D input? - How would you compute means ignoring NaN entries? - How would you return the means as an `(m, 1)` column so they can be subtracted from each row? - How would you compute a weighted mean of each row, given one weight per column?

Overview: Compute the mean of every row of a 2-D NumPy array with a single vectorized reduction. It tests how the axis argument shapes the result and how you handle empty input, 1-D input and missing values.

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

Given a 2-D NumPy array of shape (m, n), return a 1-D array of shape (m,) holding the mean of each row.

Use a vectorized NumPy reduction, with no Python loop over the rows. The input is a valid non-empty 2-D array.

Example:

import numpy as np
a = np.array([[1, 2, 3],
              [4, 5, 6]])
row_means(a)  # -> array([2., 5.])

What a Strong Answer Covers Guidance

  • Which axis the reduction runs along, and why that leaves one value per row
  • A vectorized call with no Python loop
  • The output shape and dtype, including for integer input
  • Time and space cost for an m×n array
  • How the function behaves on inputs outside the stated contract

Follow-up Questions Guidance

  • How would you handle a possibly empty array or 1-D input?
  • How would you compute means ignoring NaN entries?
  • How would you return the means as an (m, 1) column so they can be subtracted from each row?
  • How would you compute a weighted mean of each row, given one weight per column?