简体   繁体   中英

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?

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)

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])

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]

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM