w3resource

Advanced NumPy Exercises - Normalize a 5x5 array column-wise with random values

NumPy: Advanced Exercise-7 with Solution

Write a NumPy program to create a 5x5 array with random values and normalize it column-wise.

Sample Solution:

Python Code:

import numpy as np
# create a 5x5 array with random values
nums = np.random.rand(5, 5)
print("Original array elements:")
print(nums)
# compute the mean of each column
col_means = np.mean(nums, axis=0)

# normalize each column by subtracting its mean and dividing by its standard deviation
arr_normalized = (nums - col_means) / np.std(nums, axis=0)

print("Original Array:")
print(nums)
print("\nNormalized Array (column-wise):")
print(arr_normalized)

Sample Output:

Original array elements:
[[0.83858454 0.53779431 0.04162028 0.26871443 0.1940342 ]
 [0.9761744  0.71604666 0.27396056 0.31518587 0.54501194]
 [0.54896879 0.15611648 0.11122861 0.05373429 0.73362389]
 [0.09963178 0.24274453 0.85315162 0.72934953 0.0869224 ]
 [0.81961978 0.16084128 0.18108736 0.87256786 0.5897874 ]]
Original Array:
[[0.83858454 0.53779431 0.04162028 0.26871443 0.1940342 ]
 [0.9761744  0.71604666 0.27396056 0.31518587 0.54501194]
 [0.54896879 0.15611648 0.11122861 0.05373429 0.73362389]
 [0.09963178 0.24274453 0.85315162 0.72934953 0.0869224 ]
 [0.81961978 0.16084128 0.18108736 0.87256786 0.5897874 ]]

Normalized Array (column-wise):
[[ 0.58516372  0.77785141 -0.86165997 -0.58783195 -0.95594713]
 [ 1.02756813  1.56977146 -0.06275022 -0.43538767  0.46668539]
 [-0.34606249 -0.91782512 -0.62230944 -1.2930498   1.23119395]
 [-1.79085407 -0.53296347  1.92881744  0.92322901 -1.3901078 ]
 [ 0.52418471 -0.89683428 -0.38209781  1.39304041  0.64817558]]

Explanation:

In the above exercise -

nums = np.random.rand(5, 5): Create a 5x5 array with random values between 0 and 1.

col_means = np.mean(nums, axis=0): Calculate the mean of each column in nums using np.mean and specifying axis=0. This gives a 1D array with length 5 containing the column means.

arr_normalized = (nums - col_means) / np.std(nums, axis=0): Subtract the column means from nums to center the data around zero. Then, divide each element by the standard deviation of its column to normalize the data. This is known as standardization or z-score normalization. The np.std function is used to calculate the standard deviation along the columns (axis=0) and the resulting array is broadcasted to the same shape as nums so that each element can be divided by the standard deviation of its column. The normalized array is stored in arr_normalized.

Python-Numpy Code Editor:

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

Previous: Normalize a 5x5 array row-wise with random values.
Next: Find the sum along the last axis of a 3x3x3 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.