What is an axis in Numpy?

Question

In the context of this exercise, what is an axis in Numpy?

Answer

An axis is similar to a dimension. For a 2-dimensional array, there are 2 axes: vertical and horizontal.

When applying certain Numpy functions like np.mean(), we can specify what axis we want to calculate the values across.

For axis=0, this means that we apply a function along each “column”, or all values that occur vertically.

For axis=1, this means that we apply a function along each “row”, or all values horizontally.

Example

# Given the following 2-dimensional array
values = np.array([
[10, 20, 30, 40],
[50, 60, 70, 80],
])

# Axis=0
# along each "column"
print np.mean(values, axis=0) 
# [30, 40, 50, 60]

# Axis=1
# along each "row"
print np.mean(values, axis=1)
# [25, 65]
2 Likes

If you are having trouble grasping what axis means just remember that you are removing that dimension when you run mean or sum on that axis.
axis=0 removes the row dimension
axis=1 removes the column dimension

It’s a bit confusing because of how (x, y) coordinates are thought to run horizontally and vertically.

3 Likes

I believe that this quiz question and answer are poorly worded.
capture

If this is an array [1,2,3,4]
… and this is another [6,7,8,9]

then, as a two-dimensional array, we have
[[1,2,3,4],
[6,7,8,9]]

To my way of thinking, the “values that share an array” are [1,2,3,4] and [6,7,8,9], which lie along axis 0 and “values that share an index” are for instance, [4, 9], for index = 2 along axis 1.

How is my thinking wrong?

5 Likes

@patrickd314: I totally agree… had me confused for a while. But somewhat clearer now.