Skip to content
Advertisement

How to subtract 1d array from 2d array’s rows in Numpy

What I want to do is to subtract 1d array from other 2d array’s rows. I found, in some case, result was wrong and confused me. Below code worked good as I wanted.

lst1 = [[10,11,12,13,14], [20,21,22,23,24], [30,31,32,33,34]]
lstave = [10,20,30,40,50]
# lstave = [0.1,0.2,0.3,0.4,0.5]  # <- This is also no problem.
# transform them to nparray.
arr1 = np.array(lst1).reshape(3,5)
arrave = np.array(lstave)


for i in range(len(lst1)):
    print(arr1[i] - arrave)
    # print(np.subtract(arr1[i], arrave))   # <- This is also work

Then I got following as expected.

[  0  -9 -18 -27 -36]
[ 10   1  -8 -17 -26]
[ 20  11   2  -7 -16]

However, when I change the array “lstave” to [1, 2, 3, 4, 5] and subtract,

lst1 = [[10,11,12,13,14], [20,21,22,23,24], [30,31,32,33,34]]
lstave = [1,2,3,4,5]
arr1 = np.array(lst1).reshape(3,5)
arrave = np.array(lstave)

for i in range(len(lst1)):
    print(arr1[i] - arrave)

I got following.

[9 9 9 9 9]
[19 19 19 19 19]
[29 29 29 29 29]

I cannot understand why the only 1st element subtraction performed 5 times. I feel that broadcast is working wrong way, but I don’t know how to fix this. Can someone help me out? Thank you,

Advertisement

Answer

It does actually work, just:

10 - 1

Gives:

9

But:

11 - 2

Also gives:

9

This is more of a math question.

[10 - 1, 11 - 2, 12 - 3, 13 - 4, 14 - 5]

Would give:

[9, 9, 9, 9, 9]

So your code works.

If you make arrave to be:

[0, 1, 2, 3, 4]

All the final values would be 10.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement