Home > Enterprise >  How can I divide each row in a numpy matrix by the last element of that same row, without using loop
How can I divide each row in a numpy matrix by the last element of that same row, without using loop

Time:04-02

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.

CodePudding user response:

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.

CodePudding user response:

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