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.
np.array(a)is a 2d array, and you can sum overaxis=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]]].