Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding axes in NumPy

Tags:

python

numpy

I was going through NumPy documentation, and am not able to understand one point. It mentions, for the example below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a length of 2, the second dimension has a length of 3.

 [[ 1., 0., 0.],
 [ 0., 1., 2.]]

How does the first dimension (axis) have a length of 2?

Edit: The reason for my confusion is the below statement in the documentation.

The coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one axis. That axis has a length of 3.

In the original 2D ndarray, I assumed that the number of lists identifies the rank/dimension, and I wrongly assumed that the length of each list denotes the length of each dimension (in that order). So, as per my understanding, the first dimension should be having a length of 3, since the length of the first list is 3.

like image 609
flamingo_stark Avatar asked Mar 16 '26 15:03

flamingo_stark


2 Answers

In numpy, axis ordering follows zyx convention, instead of the usual (and maybe more intuitive) xyz.

Visually, it means that for a 2D array where the horizontal axis is x and the vertical axis is y:

    x -->
y      0   1   2
|  0 [[1., 0., 0.],
V  1  [0., 1., 2.]]

The shape of this array is (2, 3) because it is ordered (y, x), with the first axis y of length 2.

And verifying this with slicing:

import numpy as np

a = np.array([[1, 0, 0], [0, 1, 2]], dtype=np.float)

>>> a
Out[]:
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  2.]])

>>> a[0, :]                    # Slice index 0 of first axis
Out[]: array([ 1.,  0.,  0.])  # Get values along second axis `x` of length 3

>>> a[:, 2]                    # Slice index 2 of second axis
Out[]: array([ 0.,  2.])       # Get values along first axis `y` of length 2
like image 50
FabienP Avatar answered Mar 18 '26 04:03

FabienP


You may be confusing the other sentence with the picture example below. Think of it like this: Rank = number of lists in the list(array) and the term length in your question can be thought of length = the number of 'things' in the list(array)

I think they are trying to describe to you the definition of shape which is in this case (2,3)

in that post I think the key sentence is here:

In NumPy dimensions are called axes. The number of axes is rank.

like image 37
MattR Avatar answered Mar 18 '26 03:03

MattR