Python笔记 ＋

# numpy.ndarray基本概念

NumPy

numpy是事实上python生态里面用来科学计算最最重要的基础构建包，无数高级厉害的东西，都是建立在numpy基础上。

• numpy主要用于同类型多维数据的快速计算，其ndarray中的nd，就是N-dimensional的缩写；
• numpy快，是因为它底层是C写的；
• numpy表达式是向量化的（vectorization），即用一行更像数学公式的代码，来代替一大堆嵌套的for-loops（底层有for，只是我们看不到）；
``````>>> import numpy as np
>>> np.version.version
'1.19.0'
>>>
>>> a = np.arange(20).reshape(4,5)
>>> a
array([[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> a.shape
(4, 5)
>>> a.ndim
2
>>> a.dtype
dtype('int32')
>>> a.dtype.name
'int32'
>>> a.size
20
>>> a.itemsize
4
>>> a.strides
(20, 4)
>>> type(a)
<class 'numpy.ndarray'>
``````

ndarray.ndim the number of axes (dimensions) of the array.

ndarray.shape the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.

ndarray.size the total number of elements of the array. This is equal to the product of the elements of shape.

ndarray.dtype an object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.

ndarray.itemsize the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8), while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.

ndarray.data the buffer containing the actual elements of the array. Normally, we won’t need to use this attribute because we will access the elements in an array using indexing facilities.

ndarray.strides are necessary to interpret computer memory, which stores elements linearly, as multidimensional arrays. They describe the number of bytes to move forward in memory to jump from row to row, column to column, and so forth. Consider, for example, a two-dimensional array of floating-point numbers with shape (4, 3), where each element occupies 8 bytes in memory. To move between consecutive columns, we need to jump forward 8 bytes in memory, and to access the next row, 3 × 8 = 24 bytes. The strides of that array are therefore (24, 8). NumPy can store arrays in either C or Fortran memory order, iterating first over either rows or columns. This allows external libraries written in those languages to access NumPy array data in memory directly.

numpy使用axis这个词来代表维度，axis的复数是axes，我们一般说一个ndarray有多少axis，就是表示它是几维的数据。真正的数据本身，都是在最高维度内存放着的！而低维度的axis，存放的是其它axis而已。

-- EOF --

### 留言区 