In-depth understanding of NumPy concise tutorial --- array 2, numpy concise tutorial
NumPy array (2. Array Operations)
Basic operations
Array arithmetic operations are performed by elements one by one. After the array operation, a new array containing the operation result will be created.
>>> 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 one by one based on elements. The dot function or the matrix object can be used for matrix multiplication (will be introduced in subsequent chapters)
>>> A = np. array ([[1, 1],... [0, 1])> B = np. array ([2, 0],... [3, 4]) >>> A * B # multiply elements by array ([[2, 0], [0, 4]) >>> np. dot (A, B) # multiply the matrix by array ([[5, 4], [3, 4])
Some operators such as + = and * = are used to change 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 to integer type >>> a array ([[6, 6, 6], [6, 6, 6])
When an array stores different types of elements, the array uses the data type that occupies more bits as its own data type, that is, the Data Type tends to be more precise (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. These methods need to be called by instances of the ndarray class during use.
>>> 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 regard arrays as a one-dimensional linear list. However, you can perform 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) # Calculate the sum of each column, pay attention to understanding the meaning of the axis, refer to the first article of the array ([12, 15, 18, 21]) >>> B. min (axis = 1) # obtain the minimum value of each row array ([0, 4, 8])> B. cumsum (axis = 1) # Calculate the accumulation and array of each row ([0, 1, 3, 6], [4, 9, 15, 22], [8, 17, 27, 38])
Indexing, slicing, and iteration
Like the list and other Python sequences, one-dimensional arrays can be indexed, sliced, and iterated.
>>> A = np. arange (10) ** 3 # Remember, operators are processed by element in the array! >>> A array ([0, 1, 8, 27, 64,125,216,343,512,729]) >>> a [2] 8 >>> a [] array ([8, 27, 64]) >>> a [: 6: 2] =-1000 # equivalent to a [] =-1000, starting from 6th, assign a value to each element as-1000 >>>> a array ([-1000, 1,-1000, 27,-1000,125,216,343,512,729]) >>> [:: -1] # invert a array ([729,512,343,216,125,-1000, 27,-1000, 1,-1000]) >>> for I in :... print I ** (1/3 .),... nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0
Multi-dimensional arrays can have an index for each axis. These indexes are given by a comma-separated tuples.
>>> Def f (x, y ):... return 10 * x + y...> B = np. fromfunction (f, (5, 4), dtype = int) # fromfunction is a function, which will be introduced in the next article. >>> 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] # the same effect as the previous one. array ([1, 11, 21, 31, 41]) >>> B [,:] # array ([10, 11, 12, 13], [20, 21, 22, 23])
When less than the number of provided indexes is less than the number of axes, the given values are replicated in the order of rank. If the index is incorrect, the entire slice is used by default:
>>> B [-1] # The last line is equivalent to B [-1,:], and-1 is the first axis. What is missing is:, which is equivalent to the whole slice. Array ([40, 41, 42, 43])
The expressions in B [I] are treated as I and a series:, to represent the remaining axis. NumPy also allows you to use "points" like B [I,...].
Point (...) Represents the semicolon necessary for many to generate a complete index tuples. If x is an array with a rank of 5 (that is, it has five axes), then:
- X [1, 2,…] Equivalent to x [1, 2,:,:],
- X [..., 3] is equivalent to x [:, 3].
- X [4 ,..., 5,:] is equivalent to x [4,:,:, 5,:]
>>> C = array ([[0, 1, 2], # 3D array (composed of two 2-dimensional arrays )... [10, 12, 13],... [[100,101,102],... [110,112,113])> c. shape (2, 2, 3) >>> c [1,...] # equivalent to c [1,:,:] or c [1] array ([[100,101,102], [110,112,113])> c [..., 2] # equivalent to c [:,:, 2] array ([2, 13], [102,113])
Multi-dimensional array traversal 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 43