w3resource

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

NumPy: Advanced Exercise-5 with Solution

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

Sample Solution:

Python Code:

import numpy as np
# Generate a 3x3 array with random values
nums = np.random.rand(3, 3)
print("Original array elements:")
print(nums)
# Compute the mean of each column
col_means = np.mean(nums, axis=0)
print("\nMean of each row:")
print(col_means)
# Subtract the mean of each column from each element
print("\nSubtract the mean of each row from each element:")
result = nums - col_means
print(result)

Sample Output:

Original array elements:
[[0.26932492 0.0151877  0.26077975]
 [0.07798544 0.31104472 0.37382605]
 [0.06486036 0.77784151 0.91056512]]

Mean of each row:
[0.13739024 0.36802464 0.51505697]

Subtract the mean of each row from each element:
[[ 0.13193468 -0.35283694 -0.25427722]
 [-0.0594048  -0.05697992 -0.14123093]
 [-0.07252988  0.40981687  0.39550815]]

Explanation:

In the above exercise -

nums = np.random.rand(3, 3): This statement creates a 3x3 array nums filled with random values between 0 and 1.

col_means = np.mean(nums, axis=0): This statement calculates the mean of each column of nums using the np.mean() function and specifying axis=0 as the argument. The resulting array col_means contains the means of each column.

result = nums - col_means: This code subtracts the column means stored in col_means from each element in the corresponding column of nums. This creates a new array result that has been normalized column-wise.

Python-Numpy Code Editor:

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

Previous: Subtract the mean of each row from each element of a 3x3 array.
Next: Normalize a 5x5 array row-wise with random values.

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.