w3resource

Advanced NumPy Exercises - Subtract the mean of each row from each element of a 3x3 array


Write a NumPy program to create a 3x3 array with random values and subtract the mean of each row from each element.

To manipulate a 3x3 array with random values in NumPy, you can start by generating the array using numpy.random.rand. To normalize each row, calculate the mean of each row using numpy.mean with the axis parameter set to 1. Then, reshape the row means to align with the array's dimensions and subtract these means from the corresponding elements in each row. This operation effectively centers the data by removing the row-wise mean.

Sample Solution:

Python Code:

import numpy as np
# create a 3x3 array with random values
arr = np.random.rand(3, 3)
print("Original array elements:")
print(arr)
# subtract the mean of each row from each element
row_means = np.mean(arr, axis=1, keepdims=True)
print("\nMean of each row:")
print(row_means)
arr_subtracted = arr - row_means
print("\nSubtract the mean of each row from each element:")
print(arr_subtracted)

Output:

Original array elements:
[[0.61550214 0.59670368 0.5847669 ]
 [0.73449098 0.79990957 0.42938855]
 [0.811186   0.19465177 0.93097873]]

Mean of each row:
[[0.59899091]
 [0.65459637]
 [0.6456055 ]]

Subtract the mean of each row from each element:
[[ 0.01651124 -0.00228723 -0.01422401]
 [ 0.07989461  0.14531321 -0.22520782]
 [ 0.1655805  -0.45095373  0.28537323]]

Explanation:

In the above exercise -

arr = np.random.rand(3, 3): This line of code creates a 3x3 NumPy array arr with random values between 0 and 1 using the rand() function from the np.random module.

row_means = np.mean(arr, axis=1, keepdims=True): This line computes the mean of each row in arr using the mean() function from the NumPy module. The axis=1 argument specifies that we want to compute the means along the rows, and the keepdims=True argument ensures that the resulting array has the same shape as arr with a new axis for the means.

arr_subtracted = arr - row_means: This code subtracts the row means from each element in the corresponding row of arr to obtain a new array arr_subtracted.

Python-Numpy Code Editor: