Use zip
col_totals = [ sum(x) for x in zip(*my_list) ]
Answer from Metalshark on Stack OverflowI am trying to figure out how to sum each individual row, and then each column. Here is what I have so far:
import random
rows = 3
cols = 3
def main():
values = [[0,0,0], [0,0,0], [0,0,0]]
for r in range(rows):
for c in range(cols):
values[r][c] = random.randint(1, 4)
print('List')
print(values)main()
If you want to do this without numpy:
sum_rows = [sum(x) for x in values]
sum_cols = [sum(x) for x in zip(*values)]
For larger arrays, numpy.sum is the way to go.
The other 2 answers have covered it, but for the sake of clarity, remember that 2D lists don't exist. That is a list of lists, and thinking about it that way should have helped you come to a solution. It's always worth being very specific in your own mind about different types (for example, the difference between a 2D array and a matrix in numpy, or the difference between a list and a numpy array) because colloquially referring to a type as something it's not will often give you faulty assumptions how it ought to work.
python - How do I sum the columns in 2D list? - Stack Overflow
How to sum a 2d array in Python? - Stack Overflow
python - How to calculate the sum of all columns of a 2D numpy array (efficiently) - Stack Overflow
Can you explain why/how this works? 2D array and sum()
I think this is better:
>>> x=[[1, 2],[3, 4],[5, 6]]
>>> sum(sum(x,[]))
21
You could rewrite that function as,
def sum1(input):
return sum(map(sum, input))
Basically, map(sum, input) will return a list with the sums across all your rows, then, the outer most sum will add up that list.
Example:
>>> a=[[1,2],[3,4]]
>>> sum(map(sum, a))
10
Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:
>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])
Or, to sum over rows:
>>> a.sum(axis=1)
array([ 3, 12, 21, 30])
Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.
From the Tentative Numpy Tutorial:
Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the
ndarrayclass. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying theaxisparameter you can apply an operation along the specified axis of an array:
Other alternatives for summing the columns are
numpy.einsum('ij->j', a)
and
numpy.dot(a.T, numpy.ones(a.shape[0]))
If the number of rows and columns is in the same order of magnitude, all of the possibilities are roughly equally fast:

If there are only a few columns, however, both the einsum and the dot solution significantly outperform numpy's sum (note the log-scale):

Code to reproduce the plots:
import numpy
import perfplot
def numpy_sum(a):
return numpy.sum(a, axis=1)
def einsum(a):
return numpy.einsum('ij->i', a)
def dot_ones(a):
return numpy.dot(a, numpy.ones(a.shape[1]))
perfplot.save(
"out1.png",
# setup=lambda n: numpy.random.rand(n, n),
setup=lambda n: numpy.random.rand(n, 3),
n_range=[2**k for k in range(15)],
kernels=[numpy_sum, einsum, dot_ones],
logx=True,
logy=True,
xlabel='len(a)',
)
state=[[3,2,3],[23,4,4],[5,43,3]] s=sum(state, [])
This code transforms a 2D array to 1D array (all elements of the 2D array are now elements of an 1D array). I know that sum() first parameter sums all the elements of the iterable and the second is the starting point. But i really dont get how this leads to 2D--->1D
Use numpy.add.reduceat:
import numpy as np
M = [[1,2,3],
[1,2,3],
[1,2,3]]
np.add.reduceat(M, [0, 2])
# indices [0,2] splits the list into [0,1] and [2] to add them separately,
# you can see help(np.add.reduceat) for more
# array([[2, 4, 6],
# [1, 2, 3]])
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
M[:2] = [[a + b for a, b in zip(M[0], M[1])]]
print(M) # [[5, 7, 9], [7, 8, 9]]
Things to google to understand this:
M[:2] =: python slice assignment[... for .. in ...]: python list comprehensionfor a, b in ...: python tuple unpacking loop
You need to unpack the argument to zip first.
a = [[11.9, 12.2, 12.9],
[15.3, 15.1, 15.1],
[16.3, 16.5, 16.5],
[17.7, 17.5, 18.1]]
result = [sum(x) for x in zip(*a)]
>>> [61.2, 61.3, 62.6]
If array is a variable containing your 2d array, try
[sum([row[i] for row in array]) for i in range(len(array[0]))]