How can I divide each row in a numpy matrix by the last element of that same row, without using loops?

Viewed 128

For example:

a = np.array([[ 0, 1, 1], [2, 4, 2]])

I would like for each row in array 'a' to be divided by the last element in each row so the output is as below.

array([[0, 1, 1],
       [1, 2, 1]])

I would like to apply this to a much larger array but with the same operation. I am currently doing this using for loops that take too long and can't find an equivalent function.

3 Answers

The desired result can be achieved by simple list comprehension.

answer = np.array([a[i]/a[i][-1] for i in range(0, len(a))])

What this does is that it iterated through the rows of the array a and adds the array obtained after dividing each by its last element to the final array.

Divide by a column array:

In [69]: a[:,-1]
Out[69]: array([1, 2])
In [70]: a[:,-1][:,None]
Out[70]: 
array([[1],
       [2]])
In [71]: a/a[:,-1][:,None]
Out[71]: 
array([[0., 1., 1.],
       [1., 2., 1.]])

By broadcasting rules, a (3,2) works with a (1,2)

alternate ways of getting the right column shape

In [72]: a[:,[-1]]
Out[72]: 
array([[1],
       [2]])
In [73]: a[:,-1:]
Out[73]: 
array([[1],
       [2]])

You could proceed like this :

for row in a:  # iterate over each row
    row //= row[-1]  # divide each row by last element

This gives you the wanted result and can apply to larger numpy arrays.

Related