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.
JavaScript
x
12
12
1
lst1 = [[10,11,12,13,14], [20,21,22,23,24], [30,31,32,33,34]]
2
lstave = [10,20,30,40,50]
3
# lstave = [0.1,0.2,0.3,0.4,0.5] # <- This is also no problem.
4
# transform them to nparray.
5
arr1 = np.array(lst1).reshape(3,5)
6
arrave = np.array(lstave)
7
8
9
for i in range(len(lst1)):
10
print(arr1[i] - arrave)
11
# print(np.subtract(arr1[i], arrave)) # <- This is also work
12
Then I got following as expected.
JavaScript
1
4
1
[ 0 -9 -18 -27 -36]
2
[ 10 1 -8 -17 -26]
3
[ 20 11 2 -7 -16]
4
However, when I change the array “lstave” to [1, 2, 3, 4, 5] and subtract,
JavaScript
1
8
1
lst1 = [[10,11,12,13,14], [20,21,22,23,24], [30,31,32,33,34]]
2
lstave = [1,2,3,4,5]
3
arr1 = np.array(lst1).reshape(3,5)
4
arrave = np.array(lstave)
5
6
for i in range(len(lst1)):
7
print(arr1[i] - arrave)
8
I got following.
JavaScript
1
4
1
[9 9 9 9 9]
2
[19 19 19 19 19]
3
[29 29 29 29 29]
4
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:
JavaScript
1
2
1
10 - 1
2
Gives:
JavaScript
1
2
1
9
2
But:
JavaScript
1
2
1
11 - 2
2
Also gives:
JavaScript
1
2
1
9
2
This is more of a math question.
JavaScript
1
2
1
[10 - 1, 11 - 2, 12 - 3, 13 - 4, 14 - 5]
2
Would give:
JavaScript
1
2
1
[9, 9, 9, 9, 9]
2
So your code works.
If you make arrave
to be:
JavaScript
1
2
1
[0, 1, 2, 3, 4]
2
All the final values would be 10
.