user10360186
user10360186

Reputation:

Numpy subtraction from two arrays

I have two numpy arrays like below

a=np.array([11,12])
b=np.array([9])

#a-b should be [2,12]

I want to subtract both a & b such that result should [2,12]. How can I achieve this result?

Upvotes: 3

Views: 2218

Answers (5)

Paul Panzer
Paul Panzer

Reputation: 53029

We can avoid unnecessary padding / temporaries by copying a and then subtracting b in-place:

# let numpy determine appropriate dtype
dtp = (a[:0]-b[:0]).dtype
# copy a
d = a.astype(dtp)
# subtract b
d[:b.size] -= b

Upvotes: 0

sacuL
sacuL

Reputation: 51335

A similar method to @BlownhitherMa, would be to create an array of zeros the size of a (we can call it c), then put in b's values where appropriate:

c = np.zeros_like(a)
c[np.indices(b.shape)] = b

>>> c
array([9, 0])

>>> a-c
array([ 2, 12])

Upvotes: 2

Blownhither Ma
Blownhither Ma

Reputation: 1471

You can zero-pad one of the array.

import numpy as np

n = max(len(a), len(b))
a_pad = np.pad(a, (0, n - len(a)), 'constant')
b_pad = np.pad(b, (0, n - len(b)), 'constant')

ans = a_pad - b_pad

Here np.pad's second argument is (#of left pads, #of right pads)

Upvotes: 7

hsnsd
hsnsd

Reputation: 1823

Here is a very long laid out solution.

diff =[]

n = min(len(a), len(b))
for i in range (n):
    diff.append(a[i] - b[i])
if len(a) > n:
    for i in range(n,len(a)):
        diff.append(a[i])
elif len(b) > n:
    for i in range(n,len(b)):
        diff.append(b[i])
diff=np.array(diff)
print(diff)

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use zip_longest from itertools:

import numpy as np
from itertools import zip_longest

a = np.array([11, 12])
b = np.array([9])

result = np.array([ai - bi for ai, bi in zip_longest(a, b, fillvalue=0)])
print(result)

Output

[ 2 12]

Upvotes: 1

Related Questions