I would like to sum through an array made of other sub-arrays.
import numpy as np
a1 = np.array([1,2,3])
a2 = np.array([3,4,5])
a3 = np.array([6,7,8])
a = np.concatenate(([a1],[a2],[a3]))
print(len(a))
for i in range(1,len(a)): (1)
for j in i : (2)
for k in j : (3)
goal = np.sum(np.cos(k))
print(goal)
goal to achieve :
goal = cos(1) cos(2) cos(3)
goal = cos(3) cos(4) cos(5)
goal = cos(6) cos(7) cos(8)
I thought of looping first on the array containing every other sub-array (1) , then for each sub-array (2) and finally inside each sub array (3) .
I'll get a traceback :
File "*****************", line 18, in <module>
for j in i :
TypeError: 'int' object is not iterable
In my real problem, I might have more than 3 sub-arrays. I think it can be done but I'm still discovering Python.
CodePudding user response:
You have far too many levels of looping. You just need one loop to iterate over the rows of the array, then you can sum that row.
for row in a:
goal = np.sum(np.cos(row))
print(goal)
CodePudding user response:
Instead of j in i
write j in a[i]
CodePudding user response:
In [212]: a1 = np.array([1,2,3])
...: a2 = np.array([3,4,5])
...: a3 = np.array([6,7,8])
...:
...: a = np.concatenate(([a1],[a2],[a3]))
...:
The resulting 2d array:
In [213]: a
Out[213]:
array([[1, 2, 3],
[3, 4, 5],
[6, 7, 8]])
cos of each element:
In [214]: np.cos(a)
Out[214]:
array([[ 0.54030231, -0.41614684, -0.9899925 ],
[-0.9899925 , -0.65364362, 0.28366219],
[ 0.96017029, 0.75390225, -0.14550003]])
sum rows:
In [215]: np.cos(a).sum(axis=1)
Out[215]: array([-0.86583703, -1.35997393, 1.56857251])
it's easier to verify that this is summing rows with:
In [216]: a.sum(axis=1)
Out[216]: array([ 6, 12, 21])
With numpy
it's best to think in terms of the whole multidimensional array, and actions that work on the whole thing, or on specific dimensions. This is both faster and generally more useful.