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

NumPy: Advanced Exercise-4 with Solution

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

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:")
# subtract the mean of each row from each element
row_means = np.mean(arr, axis=1, keepdims=True)
print("\nMean of each row:")
arr_subtracted = arr - row_means
print("\nSubtract the mean of each row from each element:")

Sample 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.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]]


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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find the sum of a 4x4 array containing random values.
Next: Subtract the mean of each column from each element of a 3x3 array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Decapitalizes the first letter of a string:


def tips_decapitalize(s, upper_rest=False):
  return s[:1].lower() + (s[1:].upper() if upper_rest else s[1:])
print(tips_decapitalize('PythonTips', True)) 




We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook