An in-depth understanding of numpy concise Tutorial---array 2

Source: Internet
Author: User
numpy Array (2, array operation)

Basic operations

The arithmetic operations of an array are calculated by element. The array operation creates a new array that contains the result 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 ([0, Max, Max,]) >>> b**2 Array ([1, 4, 9]) >>> 10*np.sin (a) array ([9.129452 51,-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 by element, and matrix multiplication can be achieved using the DOT function or creating a Matrix object (later chapters will describe)

>>> a= Np.array ([[...] [0,1]]) >>> b= np.array ([[2,0], ...  [3,4]]) >>> a*b # multiply elements by Array ([[[2, 0],   [0, 4]]) >>> Np.dot (A, b) # matrix multiplied by Array ([[5, 4],   [3, 4])

Some operators, such as + = and *=, are used to change an existing array without creating a new one.

>>> 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 converted to an integer type >>> a array ([[6, 6, 6],       [6, 6, 6]])

When a different type of element is stored in an array, the array uses the data type that occupies more bits (bit) as its own data type, which is a more accurate 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 ' &  gt;>> 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 the sum of all elements of the computed array, are implemented as methods of the Ndarray class and are used with an instance of the Ndarray class to invoke 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 arrays as a one-dimensional linear list. However, you can perform the corresponding operation on the specified axis by specifying the axis parameter (that is, the row of the array):

>>> b= Np.arange () reshape (3,4) >>> b Array ([[[0, 1, 2, 3],       [4, 5, 6, 7],       [8, 9, 10, 11]]) & Gt;>> B.sum (axis=0) # Calculate each column's and, note the meaning of the axis, refer to the first article of the array ([X, Max, Max]) >>> b.min (Axis=1) # Gets the minimum value for each row arr Ay ([0, 4, 8]) >>> b.cumsum (Axis=1) # Calculates the cumulative and array of each line ([[0, 1, 3, 6], [4, 9, +,       ],       [8, 17, 27, 38]])

indexes, slices, and iterations

As with lists and other Python sequences, one-dimensional arrays can be indexed, sliced, and iterated.

>>> a= Np.arange (**3) #记住, operators are handled by elements in an array! >>> a array ([0, 1, 8, 343, 216, 729]) >>> a[2] 8 >>> a[2:5] Array ([8, 27, 64 ]) >>> a[:6:2]=-1000 # is equivalent to a[0:6:2]=-1000, from start to 6th position, every other element assigns it a value of -1000 >>> a array ([-1000, 1,-1000, 27,- 216, 343, 729]) >>> a[::-1] # Invert a array ([729, +, 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 an index on each 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是一个函数, as described in the next article. >>> b Array ([[0], 1, 2, 3], [Ten, One,,], [,,       40,       41],       [42 ]]) >>> b[2,3] >>> b[0:5, 1] # The second element of each row is an array ([1, one, four, 1]) >>> b[:] # Same as the previous effect a Rray ([1, one, ten, 20]) >>> B[1:3,:] # The second and third elements of each column array ([[Ten, one, three, four],       [, 21, 22, 23]])

When fewer than the number of indexes provided, the given values are copied in order of rank, and the missing index is assumed to be the entire slice:

>>> B[-1] # The last line, equivalent to B[-1,:],-1 is the first axis, and the missing is:, equivalent to the entire slice. Array ([40, 41, 42, 43])

B[i] The expressions in brackets are treated as I and a series: to represent the remaining axes. NumPy also allows you to use "dots" like b[i,...].

Point (...) Represents many of the necessary semicolons that produce a complete set of indexes. If x is an array with a rank of 5 (that is, it has 5 axes), then:

    • x[1,2,...] is equivalent to x[1,2,:,:,:],

    • x[...,3] equivalent to x[:,:,:,:,3]

    • X[4,..., 5,:] Equal to x[4,:,:,5,:]

>>> c= Array ([[[[[[0], 1, 2], #三维数组 (two 2-dimensional arrays superimposed) ... [10, 12, 13]], ... [100,101,102], ... [110,112,113]]] >>> c.shape  (2, 2, 3) >>> c[1,...] #等同于c [1,:,:] or c[1] Array ([[[], 101, 102],       [110, 112, 113]]) >>> c[...,2] #等同于c [:,:, 2] Array ([[2],       [102, 113]])

The traversal of a multidimensional array 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 work with each element in an array, you can use the Flat property, which is an iterator to the elements of an element:

>>>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

Shape operation

Change the shape of an array

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)

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

>>> A.ravel () # Flattening arrays Array ([7., 5., 9., 3., 7., 2., 7., 8., 6., 8., 3., 2.]) >>> a.shape= (6, 2) >& Gt;> 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", that is, by the behavioral benchmark, the rightmost index changes fastest, so the element a[0,0] is followed by a[0,1]. If the array changes to another shape (reshape), the array is still "C-style". NumPy typically creates an array that holds the data in this order, so Ravel () usually does not need to create a copy of the call array. However, you may need to create a copy of an array if it is made by slicing other arrays or having unusual options. You can also have some optional parametric functions that let reshape () and Ravel () build a Fortran-style array, the leftmost index changing the fastest.

The reshape function changes the shape of the call array and returns the array, while the resize function changes the call 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 you specify a dimension of-1 in the reshape operation, the exact dimensions are calculated according to the actual situation

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.