numpy: summing every element of numpy array with every element of another

天大地大妈咪最大 提交于 2021-01-28 13:01:12

问题


I'm coming to python from Matlab. In Matlab, given two vectors that are not necessarily the same length, they can be added if one is a row vector and one is a column vector.

v1 = [1 3 5 7]

v2 = [2 4 6]'

v1 + v2

ans =

 3     5     7     9
 5     7     9    11
 7     9    11    13

I am trying to produce the same behavior in python given two numpy arrays. Looping first came to mind:

import numpy as np
v1 = np.array([1,3,5,7])
v2 = np.array([2,4,6])
v3 = np.empty((3,4,))
v3[:] = np.nan

for i in range(0,3):
    v3[i,:] = v1 + v2[i]

Is there a more concise and efficient way?


回答1:


import numpy as np

v1 = np.array([1, 3, 5, 7])
v2 = np.array([2, 4, 6])

v1 + v2[:, None]

You can read more about numpy's broadcasting rules.




回答2:


Try this out:

for i in v2:
  z = []
  for j in v1:
    z.append(i+j)
  
  print(z)


来源:https://stackoverflow.com/questions/63286737/numpy-summing-every-element-of-numpy-array-with-every-element-of-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!