Reputation: 167
Say I have a numpy array [[1,2],[3,4],[5,6]]
, how do I do element-wise mathematics such that I could iterate over each XY pair to get X^2 + Y^2 for each pair?
Upvotes: 1
Views: 78
Reputation: 1
import numpy as np
arr1 = np.array([[1,2],[3,4],[5,6]])
rows = arr1.shape[0]
cols = arr1.shape[1]
ans = []
for x in range(rows):
answer = arr1[x,0]**2 + arr1[x,1]**2
ans.append(answer)
print(ans)
Upvotes: 0
Reputation: 150735
Since you tagged numpy
:
(np.array(a)**2).sum(-1)
Output:
array([ 5, 25, 61])
Upvotes: 2