0

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])

1
  • Do you know how to add a dimension to an array? np.sum(arr, axis=1)[:,None]. The keep_dims parameter is handy, but you should also be familiar with this None idiom. Commented Oct 10, 2021 at 23:20

2 Answers 2

3

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]]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.