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.

JavaScript

Then I got following as expected.

JavaScript

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

JavaScript

I got following.

JavaScript

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

Gives:

JavaScript

But:

JavaScript

Also gives:

JavaScript

This is more of a math question.

JavaScript

Would give:

JavaScript

So your code works.

If you make arrave to be:

JavaScript

All the final values would be 10.

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