In the context of this exercise, what is an axis in Numpy?
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.
axis=0, this means that we apply a function along each “column”, or all values that occur vertically.
axis=1, this means that we apply a function along each “row”, or all values horizontally.
# Given the following 2-dimensional array
values = np.array([
[10, 20, 30, 40],
[50, 60, 70, 80],
# along each "column"
print np.mean(values, axis=0)
# [30, 40, 50, 60]
# along each "row"
print np.mean(values, axis=1)
# [25, 65]
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.
I believe that this quiz question and answer are poorly worded.
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
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?
@patrickd314: I totally agree… had me confused for a while. But somewhat clearer now.