Array formated as arr = [(1,1),(1,1)...(35,1),(35,1)]
can be confusing. It looks like an list
of tuples
. If that is what it is then, you need to use a list comprehension to make a new list:
arr1 = [(i,j, fun(i,j)) for i,j in arr]
e.g.
In [359]: arr=[(1,1),(1,2),(35,1),(35,2)]
In [360]: [(i[0],i[1], sum(i)) for i in arr]
Out[360]: [(1, 1, 2), (1, 2, 3), (35, 1, 36), (35, 2, 37)]
But you say in a comment that arr
is a numpy array.
In [361]: Arr=np.array(arr)
In [362]: Arr
Out[362]:
array([[ 1, 1],
[ 1, 2],
[35, 1],
[35, 2]])
Same numbers, but it displays as a list of lists. An array that displays as a list of tuples is a structured array, with a different dtype
.
Is the function something that can take this whole array, or must it be feed the values 2 by 2?
np.sum
takes the whole array, and can return a 2d result:
In [366]: np.sum(Arr, axis=1, keepdims=True)
Out[366]:
array([[ 2],
[ 3],
[36],
[37]])
which can be easily concatenated onto Arr
giving a new array:
In [370]: np.concatenate([Arr,np.sum(Arr, axis=1, keepdims=True)],axis=1)
Out[370]:
array([[ 1, 1, 2],
[ 1, 2, 3],
[35, 1, 36],
[35, 2, 37]])
On the other hand the Python
sum
just takes numbers. Arr
can be used in a comprehension just like the list:
In [371]: [sum(i) for i in Arr]
Out[371]: [2, 3, 36, 37]
To concatenate that onto the original, I need to turn it into a 2d 'vertical' array (as shown in Out[366])
In [376]: np.concatenate([Arr,np.array([sum(i) for i in Arr])[:,None]],axis=1)
Out[376]:
array([[ 1, 1, 2],
[ 1, 2, 3],
[35, 1, 36],
[35, 2, 37]])
append
, vstack
, hstack
are all variations on concatenate
. You could also construct a (4,3)
array, and insert the values of Arr
and new calculation.