 Bishwajit Purkaystha - 3 years ago 183
Python Question

# axis = 0 is not clearly understood in numpy.sum

I am learning Python, and have encountered

`numpy.sum`
. It has an optional parameter
`axis`
. This parameter is used to get either column-wise summation or row-wise summation. When
`axis = 0`
we imply to sum it over columns only. For example,

``````a = np.array([[1, 2, 3], [4, 5, 6]])
np.sum(a, axis = 0)
``````

This snippet of code produces output:
`array([5, 7, 9])`
, fine. But if I do:

``````a = np.array([1, 2, 3])
np.sum(a, axis = 0)
``````

I get result:
`6`
, why is that? Shouldn't I get
`array([1, 2, 3])`
? Thanks. juanpa.arrivillaga

All that is going on is that numpy is summing across the first (0th) and only axis. Consider the following:

``````In : a = np.array([1, 2, 3])

In : a.shape
Out: (3,)

In : len(a.shape) # number of dimensions
Out: 1

In : a1 = a.reshape(3,1)

In : a2 = a.reshape(1,3)

In : a1
Out:
array([,
,
])

In : a2
Out: array([[1, 2, 3]])

In : a1.sum(axis=1)
Out: array([1, 2, 3])

In : a1.sum(axis=0)
Out: array()

In : a2.sum(axis=1)
Out: array()

In : a2.sum(axis=0)
Out: array([1, 2, 3])
``````

So, to be more explicit:

``````In : a1.shape
Out: (3, 1)
``````

`a1` is 2-dimensional, the "long" axis being the first.

``````In : a1[:,0] # give me everything in the first axis, and the first part of the second
Out: array([1, 2, 3])
``````

Now, sum along the first axis:

``````In : a1.sum(axis=0)
Out: array()
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download