Skip to content Skip to sidebar Skip to footer

Understanding Axes In 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 dimensi

Solution 1:

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      012
|  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 0offirst axis
Out[]: array([ 1.,  0.,  0.])  # Getvalues along second axis `x` of length 3>>> a[:, 2]                    # Slice index 2ofsecond axis
Out[]: array([ 0.,  2.])       # Getvalues along first axis `y` of length 2

Solution 2:

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.

Solution 3:

If you print the numpy array

print(np.array([[ 1.  0.  0.],[ 0.  1.  2.]])

You'll get the following output

#col1 col2 col3[[ 1.  0.  0.]# row 1[ 0.  1.  2.]]#  row 2

Think of it as a 2 by 3 matrix... 2 rows, 3 columns. It is a 2d array because it is a list of lists. ([[ at the start is a hint its 2d)).

The 2d numpy array

np.array([[ 1.  0., 0., 6.],[ 0.  1.  2., 7.],[3.,4.,5,8.]]) 

would print as

#col1 col2 col3 col4[[ 1.  0. , 0., 6.]# row 1[ 0.  1. , 2., 7.]#  row 2[3.,  4. , 5., 8.]]# row 3

This is a 3 by 4 2d array (3 rows, 4 columns)

Solution 4:

The first dimensions is the length:

In [11]: a = np.array([[ 1., 0., 0.], [ 0., 1., 2.]])

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

In [13]: len(a)  # "length of first dimension"
Out[13]: 2

The second is the length of each "row":

In [14]: [len(aa) for aa in a]  # 3 is "length of second dimension"
Out[14]: [3, 3]

Many numpy functions take axis as an argument, for example you can sum over an axis:

In[15]: a.sum(axis=0)
Out[15]: array([ 1.,  1.,  2.])

In[16]: a.sum(axis=1)
Out[16]: array([ 1.,  3.])

The thing to note is that you can have higher dimensional arrays:

In [21]: b = np.array([[[1., 0., 0.], [ 0., 1., 2.]]])

In [22]: b
Out[22]:
array([[[ 1.,  0.,  0.],
        [ 0.,  1.,  2.]]])

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

Post a Comment for "Understanding Axes In Numpy"