+4 votes
in Programming Languages by (77.8k points)
How can I compute the average of each column of a Numpy array?

E.g.

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])

Average should be [ 7, 8, 9, 10]

1 Answer

+1 vote
by (355k points)
selected by
 
Best answer

You need to use Numpy function mean() with "axis=0" to compute average by column. To compute average by row, you need to use "axis=1".

>>> import numpy as np
>>> a=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])
>>> a.mean(axis=0)   #average by column
array([ 7.,  8.,  9., 10.])
>>> a.mean(axis=1)  #average by row
array([ 2.5,  6.5, 10.5, 14.5])


...