Back to Practice
#0037
Normalize Each Row
MediumNumPy18 min15 XP
Problem
Given a 2D NumPy array, divide each row by that row sum. If a row sum is zero, leave that row as all zeros.
Why This Matters
This pattern appears in probabilities, attention weights, transition matrices, and feature normalization.
Function Signature
def normalize_rows(matrix):
Examples
Example 1
Inputmatrix = np.array([[1, 1], [2, 6], [0, 0]])
Outputarray([[0.5, 0.5], [0.25, 0.75], [0.0, 0.0]])
Each nonzero row is divided by its own row sum. The zero row stays zero.
Constraints
- Input is a 2D numeric NumPy array.
- Use row-wise sums, not one global sum.
- Avoid division by zero for all-zero rows.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 4 hidden categories
Nonzero and zero rows
Inputnp.array([[1, 1], [2, 6], [0, 0]])
Expected[[0.5, 0.5], [0.25, 0.75], [0.0, 0.0]]
keepdims=True keeps row sums shaped for broadcasting.
Hidden Test Categories
One-row matrixRows with decimal valuesRows with negative and positive valuesMany columns