T-800
T-800

Reputation: 1603

Subtract a value from several arrays

I need to subtract a number from my numpy arrays. Let's say, we have two arrays and I need to subtract 10 from each of its elements.

a = numpy.array([10, 11, 23, 45])
b = numpy.array([55, 23, 54, 489, 45, 12])

To do that, I enter:

a - 10
b - 10

And I get the desired output, which is:

array([ 0,  1, 13, 35])
array([ 45,  13,  44, 479,  35,   2])

But, as I have lots of such arrays, I was wondering if it is possible to get the same result, for example by entering (a,b)-10?

Upvotes: 1

Views: 111

Answers (2)

John1024
John1024

Reputation: 113844

If you enter:

numpy.array((a, b)) - 10

You get the desired result:

array([[ 0  1 13 35], [ 45  13  44 479  35   2]], dtype=object)

(a,b) - 10 doesn't work because mathematical operations only work element-by-element when operating on numpy arrays. So, the solution, as above, is to put a and b into one numpy array.

Upvotes: 2

ysakamoto
ysakamoto

Reputation: 2532

numpy.array([a,b]) - 10 will work.

Upvotes: 2

Related Questions