Home >Backend Development >Python Tutorial >In-depth understanding of NumPy concise tutorial---Array 2
NumPy array (2. Array operations)
Basic operations
Array arithmetic operations are performed element by element. Array operations create a new array containing the results of the operation.
>>> a= np.array([20,30,40,50]) >>> b= np.arange( 4) >>> b array([0, 1, 2, 3]) >>> c= a-b >>> c array([20, 29, 38, 47]) >>> b**2 array([0, 1, 4, 9]) >>> 10*np.sin(a) array([ 9.12945251,-9.88031624, 7.4511316, -2.62374854]) >>> a<35 array([True, True, False, False], dtype=bool)
Unlike other matrix languages, the multiplication operator * in NumPy is calculated element by element. Matrix multiplication can be implemented using the dot function or creating a matrix object (subsequent Chapter will introduce)
>>> A= np.array([[1,1], ...[0,1]]) >>> B= np.array([[2,0], ...[3,4]]) >>> A*B # 逐个元素相乘 array([[2, 0], [0, 4]]) >>> np.dot(A,B) # 矩阵相乘 array([[5, 4], [3, 4]])
Some operators such as += and *= are used to modify an existing array without creating a new array.
>>> a= np.ones((2,3), dtype=int) >>> b= np.random.random((2,3)) >>> a*= 3 >>> a array([[3, 3, 3], [3, 3, 3]]) >>> b+= a >>> b array([[ 3.69092703, 3.8324276, 3.0114541], [ 3.18679111, 3.3039349, 3.37600289]]) >>> a+= b # b转换为整数类型 >>> a array([[6, 6, 6], [6, 6, 6]])
When the array stores elements of different types, the array will use the data type that occupies more bits as its own data type , which is to favor more precise data types (this behavior is called upcast).
>>> a= np.ones(3, dtype=np.int32) >>> b= np.linspace(0,np.pi,3) >>> b.dtype.name 'float64' >>> c= a+b >>> c array([ 1., 2.57079633, 4.14159265]) >>> c.dtype.name 'float64' >>> d= exp(c*1j) >>> d array([ 0.54030231+0.84147098j,-0.84147098+0.54030231j, -0.54030231-0.84147098j]) >>> d.dtype.name 'complex128'
Many non-array operations, such as calculating the sum of all elements of an array, are implemented as methods of the ndarray class. When using them, an instance of the ndarray class is required. Call these methods.
>>> a= np.random.random((2,3)) >>> a array([[ 0.65806048, 0.58216761, 0.59986935], [ 0.6004008, 0.41965453, 0.71487337]]) >>> a.sum() 3.5750261436902333 >>> a.min() 0.41965453489104032 >>> a.max() 0.71487337095581649
These operations treat the array as a one-dimensional linear list. However, you can perform corresponding operations on the specified axis by specifying the axis parameter (that is, the row of the array):
>>> b= np.arange(12).reshape(3,4) >>> b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> b.sum(axis=0) # 计算每一列的和,注意理解轴的含义,参考数组的第一篇文章 array([12, 15, 18, 21]) >>> b.min(axis=1) # 获取每一行的最小值 array([0, 4, 8]) >>> b.cumsum(axis=1) # 计算每一行的累积和 array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]])
Indexing, slicing and iteration
Like lists and other Python sequences, one-dimensional arrays can be indexed, sliced, and iterated.
>>> a= np.arange(10)**3 #记住,操作符是对数组中逐元素处理的! >>> a array([0, 1, 8, 27, 64, 125, 216, 343, 512, 729]) >>> a[2] 8 >>> a[2:5] array([ 8, 27, 64]) >>> a[:6:2]= -1000 # 等同于a[0:6:2]= -1000,从开始到第6个位置,每隔一个元素将其赋值为-1000 >>> a array([-1000, 1,-1000, 27,-1000, 125, 216, 343, 512, 729]) >>> a[: :-1] # 反转a array([ 729, 512, 343, 216, 125,-1000, 27,-1000, 1,-1000]) >>>for i in a: ... print i**(1/3.), ... nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0
Multidimensional arrays can have one index per axis. The indices are given as a comma-separated tuple.
>>>def f(x,y): ... return 10*x+y ... >>> b= np.fromfunction(f,(5,4),dtype=int) #fromfunction是一个函数,下篇文章介绍。 >>> b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) >>> b[2,3] 23 >>> b[0:5, 1] # 每行的第二个元素 array([ 1, 11, 21, 31, 41]) >>> b[: ,1] # 与前面的效果相同 array([ 1, 11, 21, 31, 41]) >>> b[1:3,: ] # 每列的第二和第三个元素 array([[10, 11, 12, 13], [20, 21, 22, 23]])
When the number of indexes provided is less than the number of axes, the given values are copied in order of rank, and the missing index defaults to is the entire slice:
>>> b[-1] # 最后一行,等同于b[-1,:],-1是第一个轴,而缺失的认为是:,相当于整个切片。 array([40, 41, 42, 43])
The expression in brackets in b[i] is treated as i and a series of : to represent the remaining axes. NumPy also allows you to use "points" like b[i,...].
The dots (…) represent the number of semicolons necessary to produce a complete index tuple. If x is an array of rank 5 (i.e. it has 5 axes), then:
x[1,2,…] is equivalent to x[1,2,:,: ,:],
x[…,3] is equivalent to x[:,:,:,:,3]
>>> c= array( [ [[ 0, 1, 2], #三维数组(两个2维数组叠加而成) ...[ 10, 12, 13]], ... ...[[100,101,102], ...[110,112,113]]] ) >>> c.shape (2, 2, 3) >>> c[1,...] #等同于c[1,:,:]或c[1] array([[100, 101, 102], [110, 112, 113]]) >>> c[...,2] #等同于c[:,:,2] array([[ 2, 13], [102, 113]])
Traversal of multi-dimensional arrays It is based on the first axis:
>>>for row in b: ... print row ... [0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43]
If you want to process each element in the array, you can use the flat attribute, which is An array element iterator:
>>>for element in b.flat: ... print element, ... 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43Shape operation
The shape of the array depends on the number of elements on each axis:
>>> a= np.floor(10*np.random.random((3,4))) >>> a array([[ 7., 5., 9., 3.], [ 7., 2., 7., 8.], [ 6., 8., 3., 2.]]) >>> a.shape (3, 4)
can be used Modify the shape of the array in various ways:
>>> a.ravel() # 平坦化数组 array([ 7., 5., 9., 3., 7., 2., 7., 8., 6., 8., 3., 2.]) >>> a.shape= (6, 2) >>> a.transpose() array([[ 7., 9., 7., 7., 6., 3.], [ 5., 3., 2., 8., 8., 2.]])
The order of array elements flattened by ravel() is usually "C-style", that is, based on behavior , the rightmost index changes fastest, so element a[0,0] is followed by a[0,1]. If the array is reshaped into another shape, the array is still "C-style". NumPy usually creates an array holding the data in this order, so ravel() usually does not need to create a copy of the calling array. But if the array is sliced through another array or has unusual options, you may need to create a copy of it. You can also use some optional parameter functions to let reshape() and ravel() construct a FORTRAN-style array, that is, the leftmost index changes the fastest.
The reshape function changes the shape of the calling array and returns the array, while the resize function changes the calling array itself.
>>> a array([[ 7., 5.], [ 9., 3.], [ 7., 2.], [ 7., 8.], [ 6., 8.], [ 3., 2.]]) >>> a.resize((2,6)) >>> a array([[ 7., 5., 9., 3., 7., 2.], [ 7., 8., 6., 8., 3., 2.]])
If a dimension is specified as -1 in the reshape operation, its accurate dimension will be calculated based on the actual situation
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more in-depth understanding of NumPy’s concise tutorial---Array 2 related articles, please pay attention to the PHP Chinese website!