Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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
np.array([[1,2,4], [2,5,6]])
array([7, 13])
np.sum(arr, axis=1)[:,None]
keep_dims
None
Using sum over axis 1:
sum
>>> 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]]
Add a comment
I am not sure what the array() function is, but if its just a list, then this should work:
array()
a=array([[1,2,4], [2,5,6]]) b=[[sum(x)] for x in a] #new list of answers
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
np.sum(arr, axis=1)[:,None]. Thekeep_dimsparameter is handy, but you should also be familiar with thisNoneidiom.