Numpy Adding two vectors with different sizes

前端 未结 3 1778
臣服心动
臣服心动 2021-02-03 22:02

If I have two numpy arrays of different sizes, how can I superimpose them.

a = numpy([0, 10, 20, 30])
b = numpy([20, 30, 40, 50, 60, 70])

What

相关标签:
3条回答
  • 2021-02-03 22:16

    Very similar to the one above, but a little more compact:

    l = sorted((a, b), key=len)
    c = l[1].copy()
    c[:len(l[0])] += l[0]
    
    0 讨论(0)
  • 2021-02-03 22:23

    If you know that b is higher dimension, then:

    >>> a.resize(b.shape)
    >>> c = a+b
    

    is all you need.

    0 讨论(0)
  • 2021-02-03 22:31

    This could be what you are looking for

    if len(a) < len(b):
        c = b.copy()
        c[:len(a)] += a
    else:
        c = a.copy()
        c[:len(b)] += b
    

    basically you copy the longer one and then add in-place the shorter one

    0 讨论(0)
提交回复
热议问题