The Basics
NumPy’s main object is the homogeneous(同類型的) multidimensional(多維) array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In NumPy dimensions are called?axes(軸). The number of axes is?rank.
For example, the coordinates(坐標(biāo)) 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 example pictured 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,2,3],
[4,5,6]
]
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the same as the Standard Python Library class array.array, which only handles one-dimensional arrays and offers less functionality. The more important attributes of an ndarray object are:
ndarray.ndim(維度):
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as?rank.
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 rank, or number of dimensions, ndim.
ndarray.size(元素個數(shù))
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.
An example:
>>>import numpy as np
>>> a = np.arange(15).reshape(3,5)
>>> a
array([[0,1,2,3,4],
[5,6,7,8,9],
[10,11,12,13,14]])
>>> a.shape
(3,5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>>type(a)
>>> b = np.array([6,7,8])
>>> b
array([6,7,8])
>>>type(b)