w3resource

NumPy: Subtract the mean of each row of a given matrix

NumPy: Array Object Exercise-182 with Solution

Write a NumPy program to subtract the mean of each row of a given matrix.

Sample Solution:

Python Code:

import numpy as np
print("Original matrix:\n")
X = np.random.rand(5, 10)
print(X)
print("\nSubtract the mean of each row of the said matrix:\n")
Y = X - X.mean(axis=1, keepdims=True)
print(Y)

Sample Output:

Original matrix:

[[0.59243452 0.51883289 0.03732848 0.49544926 0.22637201 0.45750412
  0.81614237 0.86681236 0.95482226 0.54789281]
 [0.26483034 0.22539348 0.67459222 0.4537891  0.48308938 0.04417623
  0.70874363 0.17837943 0.39849428 0.22924537]
 [0.96320355 0.51573012 0.40573297 0.00295715 0.44898528 0.38220344
  0.70517304 0.4808969  0.75349138 0.05258898]
 [0.08872567 0.44837943 0.62164056 0.4727482  0.45261789 0.46171551
  0.24969247 0.89204763 0.84657175 0.70570759]
 [0.14428353 0.20556412 0.97059136 0.53545871 0.93828877 0.81535277
  0.60563373 0.47543413 0.0468766  0.97460889]]

Subtract the mean of each row of the said matrix:

[[ 0.04107541 -0.03252622 -0.51403063 -0.05590985 -0.3249871  -0.09385499
   0.26478326  0.31545325  0.40346315 -0.0034663 ]
 [-0.10124301 -0.14067986  0.30851887  0.08771575  0.11701603 -0.32189712
   0.34267028 -0.18769391  0.03242094 -0.13682798]
 [ 0.49210727  0.04463384 -0.06536332 -0.46813913 -0.022111   -0.08889284
   0.23407676  0.00980062  0.2823951  -0.4185073 ]
 [-0.435259   -0.07560524  0.09765589 -0.05123647 -0.07136678 -0.06226916
  -0.2742922   0.36806296  0.32258708  0.18172292]
 [-0.42692573 -0.36564514  0.3993821  -0.03575056  0.36707951  0.24414351
   0.03442447 -0.09577513 -0.52433266  0.40339963]]

Python Code Editor:

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

Previous: Write a NumPy program to place a specified element in specified time randomly in a specified 2D array.
Next: Write a NumPy program to test whether a given 2D array has null columns or not.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}