+1 vote
in Programming Languages by (59.8k points)
In a given Numpy array, I want to select the minimum value in each column and then subtract that minimum value from each row of the column. How can I do it?

E.g.

d= [[10,  5,  8, 12],

       [ 1,  5,  6,  9],

       [26, 12,  7, 25]]

the resulting array should be:

d= [[ 9,  0,  2,  3],

       [ 0,  0,  0,  0],

       [25,  7,  1, 16]]

1 Answer

+3 votes
by (71.8k points)
selected by
 
Best answer

You can use the min() function with the argument "axis=0" to get the minimum value in each column. Then, you can subtract the minimum values from the given array.

Here is an example:

>>> import numpy as np

>>> aa = np.array([[10, 5, 8, 12], [1, 5, 6, 9], [26, 12, 7, 25]])

>>> aa

array([[10,  5,  8, 12],

       [ 1,  5,  6,  9],

       [26, 12,  7, 25]])

>>>

>>> aa.min(axis=0)

array([1, 5, 6, 9])

>>> aa = aa - aa.min(axis=0)

>>> aa

array([[ 9,  0,  2,  3],

       [ 0,  0,  0,  0],

       [25,  7,  1, 16]])

>>> 


...