user13467695
user13467695

Reputation:

How to sum arrays in nested arrays?

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

Upvotes: 0

Views: 513

Answers (2)

Jab
Jab

Reputation: 27485

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

Upvotes: 3

Agent Biscutt
Agent Biscutt

Reputation: 737

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

Upvotes: 0

Related Questions