2020年7月6日 / 249次阅读 / Last Modified 2020年9月21日



  • numpy主要用于同类型多维数据的快速计算,其ndarray中的nd,就是N-dimensional的缩写;
  • numpy快,是因为它底层是C写的;
  • numpy表达式是向量化的(vectorization),即用一行更像数学公式的代码,来代替一大堆嵌套的for-loops(底层有for,只是我们看不到);
>>> import numpy as np
>>> np.version.version
>>> 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
>>> a.dtype
>>> a.size
>>> a.itemsize
>>> 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. 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.


-- EOF --



您的电子邮箱地址不会被公开。 必填项已用*标注



©Copyright 麦新杰 Since 2019 Python笔记

go to top