I have a nested array
array([[1,2,4], [2,5,6]])
I want to sum each array in it to get:
array([[7], [13]])
How to do that? When I do np.array([[1,2,4], [2,5,6]])
it gives
array([7, 13])
CodePudding user response:
Using sum
over axis 1:
>>> a = np.array([[1,2,4], [2,5,6]])
>>> a.sum(axis=1, keepdims=True)
[[ 7]
[13]]
Or without numpy:
>>> a = [[1,2,4], [2,5,6]]
>>> [[sum(l)] for l in a]
[[7], [13]]
CodePudding user response:
I am not sure what the array()
function is, but if its just a list,
then this should work:
a=array([[1,2,4], [2,5,6]])
b=[[sum(x)] for x in a] #new list of answers