0

I have a Numpy array of the following form:

a = [[1,2,3],[4,5,6],[3,4,2]]

I want to sum all the sublists in the following form:

b = [6,15,9]

I have the following code that does it:

ss = numpy.zeros(shape = [])
for item in a:
    print item
    s = item.sum()
    print s
    b = np.append(ss,s)

Here is the result: b = [6,15,9]

Can I do it without this explicit for loop? As in is/are there a numpy function(s) that can make my life easy? This is because the array a is pretty big ~ 10^6 entries.

1
  • Are the sub_arrays of the same length? If so then np.array(a) is a 2d array, and you can sum over axis=1. Otherwise some sort of loop is required, with a list comprehension being the most compact: [sum(x) for x in [[1,2,3],[4,5,6],[3,4,2]]]. Commented Jan 4, 2014 at 6:08

1 Answer 1

3
ss = a.sum(1)

This will do if a is a numpy array. If it is a list of numpy arrays or a list-of-lists you want to use:

ss = numpy.sum(a, 1)

Thanks @DSM for improvement.

Sign up to request clarification or add additional context in comments.

3 Comments

If a is an ndarray, you could also use the method rather than the function, i.e. a.sum(1). numpy.sum(a, 1) will actually work even if a is a list-of-lists.
@Nabla thanks for your answer. Btw, why use 1 inside the paranthesis in ss = a.sum(1) ?
@AbhinavKumar The number defines the axis of the two-dimensional array along which is to be summed, see the documentation for details.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.