Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is axis indexed in numpy's array?

Tags:

python

numpy

From Numpy's tutorial, axis can be indexed with integers, like 0 is for column, 1 is for row, but I don't grasp why they are indexed this way? And How do I figure out each axis' index when coping with multidimensional array?

like image 637
Alcott Avatar asked Jun 13 '13 04:06

Alcott


People also ask

What is the axis in NumPy array?

NumPy axes are the directions along the rows and columns. Just like coordinate systems, NumPy arrays also have axes. In a 2-dimensional NumPy array, the axes are the directions along the rows and columns.

What is axis 2 in NumPy array?

along an axis. Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1). Many operation can take place along one of these axes.

How do NumPy axes work?

Numpy Axis in Python for SumWhen we use the numpy sum() function on a 2-d array with the axis parameter, it collapses the 2-d array down to a 1-d array. It collapses the data and reduces the number of dimensions. But which axis will collapse to return the sum depends on whether we set the axis to 0 or 1.

Does NumPy array have index?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


2 Answers

By definition, the axis number of the dimension is the index of that dimension within the array's shape. It is also the position used to access that dimension during indexing.

For example, if a 2D array a has shape (5,6), then you can access a[0,0] up to a[4,5]. Axis 0 is thus the first dimension (the "rows"), and axis 1 is the second dimension (the "columns"). In higher dimensions, where "row" and "column" stop really making sense, try to think of the axes in terms of the shapes and indices involved.

If you do .sum(axis=n), for example, then dimension n is collapsed and deleted, with each value in the new matrix equal to the sum of the corresponding collapsed values. For example, if b has shape (5,6,7,8), and you do c = b.sum(axis=2), then axis 2 (dimension with size 7) is collapsed, and the result has shape (5,6,8). Furthermore, c[x,y,z] is equal to the sum of all elements b[x,y,:,z].

like image 162
nneonneo Avatar answered Sep 30 '22 10:09

nneonneo


If at all anyone need this visual description of a shape=(3,5) array:

Numpy array axis 0 and 1

like image 30
debaonline4u Avatar answered Sep 30 '22 09:09

debaonline4u