Editor

Center Each Row

Advanced · Write the code · from NumPy Broadcasting: Operate on Arrays of Different Shapes

From the lesson: NumPy Broadcasting: Operate on Arrays of Different Shapes

You've already seen that np.array([1,2,3]) 2 multiplies every element by 2. But have you wondered how* NumPy knows to stretch that single number 2 across the entire array? That mechanism is called broadcasting.

Read the lesson

Given the matrix below, subtract each row's mean from that row (center each row). You'll need np.newaxis or .reshape(-1, 1) to make the shapes compatible. Print the centered matrix.

data = np.array([[10, 20, 30],
                 [40, 50, 60],
                 [70, 80, 90]])
import numpy as np
data = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
# Subtract each row's mean from that row

More NumPy Broadcasting exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz