Add two numpy arrays with an offset
Asked Answered
A

3

5

Lets say I have two arrays:

a = numpy.array([1,2,3,4,5])
b = numpy.array([10,11,12])

I wish to add these arrays together, but I wish to start at index 3 in the first array, to produce:

numpy.array([1,2,3,14,16,12]).

So I'm basically adding an extra 0 to a[3:] to make it the same length as b, and then adding this with b, before appending this result to a[:3].

Can this be done in one step in numpy or do I just implement each of these steps?

def insert(data1, data2, offset):
    c = numpy.zeros(len(data2) + offset )
    c[:len(data1)] = data1
    c[offset:] += data2
    return c
Amick answered 8/8 at 10:14 Comment(1)
you just implement the steps separately: c = numpy.zeros(6); c[:5] = a; c[3:] += bHaplosis
S
6

You could create the output and add the chunks one by one:

offset = 3
out = np.zeros(max(len(a), offset+len(b)), dtype=a.dtype)
out[:len(a)] = a
out[offset:offset+len(b)] += b

Another robust option is to use pad:

a = np.array([1,2,3,4,5])
b = np.array([10,11,12])

offset = 3
diff = offset+len(b)-len(a)

out = (np.pad(a, [0, max(0, diff)])
      +np.pad(b, [offset, max(0, -diff)])
      )

Output:

array([ 1,  2,  3, 14, 16, 12])

Note that this type of operation is easily done with , since there in an index:

import pandas as pd

sa = pd.Series(a)
sb = pd.Series(b)
sb.index += 3

out = sa.add(sb, fill_value=0)

Output:

0     1.0
1     2.0
2     3.0
3    14.0
4    16.0
5    12.0
dtype: float64
Sacerdotal answered 8/8 at 10:36 Comment(0)
B
3

Another possible solution, which calculates, separately, the several components of the result and hence concatenates all calculated components:

n = 3

lena = len(a)
lenb = len(b)
idx1 = min(lena, n+lenb)
idx2 = min(lenb, lena-n)

np.concatenate([
    a[:n], # first part of the result
    a[n:idx1] + b[:idx2], # the part that is summed 
    a[idx1:], # may be an empty array
    b[idx2:]]) # may be an empty array

Output:

array([ 1,  2,  3, 14, 16, 12])
Barilla answered 8/8 at 16:31 Comment(0)
C
0
import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([10, 11, 12])

partToPad = a[3:]
print(partToPad)#[4 5]

padded_part = np.pad(partToPad, (0,len(b) - len(partToPad)) , mode='constant')
print(padded_part)#[4 5 0]

added_part = np.add(padded_part, b)
print(added_part)#[14 16 12]

res = np.concatenate((a[:3],added_part))
print(res)#[ 1  2  3 14 16 12]
Cassowary answered 13/9 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.