An in depth understanding of NumPy's concise tutorial array 2

  • 2020-05-19 05:06:20
  • OfStack

NumPy array (2. Operation of array)

Basic operation

The arithmetic operation of an array is one element at a time. After the array operation, a new array containing the result of the operation is 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 element by element, and matrix multiplication can be implemented using dot functions or by creating matrix objects (described in a later section)


>>> A= np.array([[1,1], 
...[0,1]]) 
>>> B= np.array([[2,0], 
...[3,4]]) 
>>> A*B #  Multiply by element  
array([[2, 0], 
     [0, 4]]) 
>>> np.dot(A,B) #  Matrix multiplication  
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 Convert to integer type  
>>> a 
array([[6, 6, 6], 
      [6, 6, 6]]) 

When different types of elements are stored in an array, the array will use the more bite-occupied (bit) data type as its own data type, that is, in favor of the more precise data type (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 the elements of an array, are implemented as methods of the ndarray class, which are called with an instance of the ndarray class.


>>> 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 an array as a 1-dimensional linear list. However, the specified axis can be computed by specifying the axis parameter (that is, the rows 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 each 1 The sum of the columns, note the meaning of the axis, the reference array 1 article  
array([12, 15, 18, 21]) 
>>> b.min(axis=1) #  For each 1 Row minimum  
array([0, 4, 8]) 
>>> b.cumsum(axis=1) #  Calculate each 1 Cumulative sum of rows  
array([[ 0, 1, 3, 6], 
      [ 4, 9, 15, 22], 
      [ 8, 17, 27, 38]]) 

Indexing, slicing, and iteration

Like lists and other Python sequences, 1-dimensional arrays can be indexed, sliced, and iterated.


>>> a= np.arange(10)**3 # Remember, the operator handles the array element by element!  
>>> 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 #  Is equivalent to a[0:6:2]= -1000 From the beginning to the end 6 Every other location 1 Each element assigns it a value of -1000 
>>> a 
array([-1000, 1,-1000, 27,-1000, 125, 216, 343, 512, 729]) 
>>> a[: :-1] #  reverse 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 1 index per axis. These indexes are given by a comma-separated tuple.


>>>def f(x,y): 
...  return 10*x+y 
... 
>>> b= np.fromfunction(f,(5,4),dtype=int) #fromfunction is 1 Function, the next article introduces.  
>>> 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] #  Each row of the first 2 An element  
array([ 1, 11, 21, 31, 41]) 
>>> b[: ,1] #  Same as before  
array([ 1, 11, 21, 31, 41]) 
>>> b[1:3,: ] #  Each column of the first 2 And the first 3 An element  
array([[10, 11, 12, 13], 
      [20, 21, 22, 23]]) 

When the number of indexes provided is less than the number of axes, the values given are copied in order of rank, and the index that is missing is the whole slice by default:


>>> b[-1] #  The last 1 Okay, so that equals b[-1,:] . -1 Is the first 1 And the missing one is:, which is equivalent to the whole slice.  
array([40, 41, 42, 43]) 

The expressions in parentheses in b[i] are used as i and the 1 series: to represent the remaining axes. NumPy also allows you to use "dots" like b[i,...] .

Point (...). Represents many semicolons necessary to produce a complete index tuple. If x is an array of rank 5 (that is, it has 5 axes), then:

x [1, 2,... Equivalent x [1, 2,,,,,,]. x[...,3] is equivalent to x[:,:,:,:,3] x [4,..., 5:] equivalent x [4,,,,,, :)

>>> c= array( [ [[ 0, 1, 2], #3 Dimension array (two 2 Dimensional array superimposed)  
...[ 10, 12, 13]], 
... 
...[[100,101,102], 
...[110,112,113]]] ) 
>>> c.shape 
 (2, 2, 3) 
>>> c[1,...] # Is equivalent to c[1,:,:] or c[1] 
array([[100, 101, 102], 
      [110, 112, 113]]) 
>>> c[...,2] # Is equivalent to c[:,:,2] 
array([[ 2, 13], 
      [102, 113]]) 

The traversal of the multidimensional array is based on the first axis:


>>> A= np.array([[1,1], 
...[0,1]]) 
>>> B= np.array([[2,0], 
...[3,4]]) 
>>> A*B #  Multiply by element  
array([[2, 0], 
     [0, 4]]) 
>>> np.dot(A,B) #  Matrix multiplication  
array([[5, 4], 
     [3, 4]]) 
0

If you want to process every element in an array, you can use the flat attribute, which is an array element iterator:


>>> A= np.array([[1,1], 
...[0,1]]) 
>>> B= np.array([[2,0], 
...[3,4]]) 
>>> A*B #  Multiply by element  
array([[2, 0], 
     [0, 4]]) 
>>> np.dot(A,B) #  Matrix multiplication  
array([[5, 4], 
     [3, 4]]) 
1

More on []... , newaxis, ndenumerate, indices, index exp refer to the NumPy example for the content

Shape (shape) operation

Change the shape of the array

The shape of the array depends on the number of elements on each axis:


>>> A= np.array([[1,1], 
...[0,1]]) 
>>> B= np.array([[2,0], 
...[3,4]]) 
>>> A*B #  Multiply by element  
array([[2, 0], 
     [0, 4]]) 
>>> np.dot(A,B) #  Matrix multiplication  
array([[5, 4], 
     [3, 4]]) 
2

You can modify the shape of an array in several ways:


>>> a.ravel() #  Flattened array  
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 the array elements flattened by ravel() is usually "C style," meaning that the right-most index changes the fastest on a behavioral basis, so a[0,0] is followed by a[0,1]. If the array changes to another shape (reshape), the array is still "C style." NumPy usually creates an array that holds 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 other arrays or has unusual options, you may need to create a copy of it. You can also use some optional parameter functions to get reshape() and ravel() to build FORTRAN style arrays, where the leftmost index changes the fastest.

The reshape function changes the shape of the calling array and returns it, while the resize function changes the calling array itself.


>>> A= np.array([[1,1], 
...[0,1]]) 
>>> B= np.array([[2,0], 
...[3,4]]) 
>>> A*B #  Multiply by element  
array([[2, 0], 
     [0, 4]]) 
>>> np.dot(A,B) #  Matrix multiplication  
array([[5, 4], 
     [3, 4]]) 
4

If a dimension is specified as -1 in the reshape operation, its exact dimension will be calculated based on the actual situation


Related articles: