[Reprint] numpy——ndarray

Reference link: numpy.diagflat in Python

numpy is an indispensable third-party library for data analysis using python. Many scientific computing tools are developed based on numpy. 

The ndarray object is a multidimensional array used to store elements of the same type. It is one of the basic objects in numpy, and the other is a func object. The main contents of this article are: 1. A brief introduction to ndarray objects; 2. Common attributes of ndarray objects; 3. How to create ndarray objects; 4. ndarray element access. Its dimension and the number of elements in each dimension are determined by shape. 

1 numpy.ndarray() 

The function in the title is the numpy constructor, we can use this function to create an ndarray object. The constructor has the following optional parameters: 

Parameter type function shape int type tuple shape of multidimensional array dtype data-type type of elements in the array buffer used to initialize the array buffer offset int buffer used to initialize the first data of the array offset strides int type tuple for each axis When the subscript increases by 1, the number of bytes that the data pointer increases in the memory. Order'C' or'F''C': row first;'F': column first Example: 

>>> np.ndarray(shape=(2,3), dtype=int, buffer=np.array([1,2,3,4,5,6,7]), offset=0, order="C") 

array([[1, 2, 3],

   [4, 5, 6]])

>>> np.ndarray(shape=(2,3), dtype=int, buffer=np.array([1,2,3,4,5,6,7]), offset=0, order="F")

array([[1, 3, 5],

   [2, 4, 6]])

>>> np.ndarray(shape=(2,3), dtype=int, buffer=np.array([1,2,3,4,5,6,7]), offset=8, order="C") 

array([[2, 3, 4],

   [5, 6, 7]])

 

2 Common attributes of ndarray objects 

Next, introduce the most commonly used attributes of ndarray objects 

T-Transpose, the same as self.transpose( ), if the dimension is less than 2, return self size-the number of elements in the array itemssize-the byte length of a single element in the array dtype-the data type object of the array element ndim-the dimension of the array shape-the shape of the array data-points to the python buffer object storing the array data flat-returns the one-dimensional iterator imag of the array-returns the imaginary part of the array real-returns the real part of the array nbytes-examples of the byte length of all elements in the array: 

>>> a = np.array(range(15)).reshape(3,5)

>>> a

array([[ 0,  1,  2,  3,  4],

   [ 5,  6,  7,  8,  9],

   [10, 11, 12, 13, 14]])

>>> a.T

array([[ 0,  5, 10],

   [ 1,  6, 11],

   [ 2,  7, 12],

   [ 3,  8, 13],

   [ 4,  9, 14]])

>>> a.size

15

>>> a.itemsize

8

>>> a.ndim

2

>>> a.shape

(3, 5)

>>> a.dtype

dtype('int64')

 

3 Create ndarray 

3.1 array 

Use the array function to create an array from a regular python list or tuple. The type of the element is determined by the element type in the original sequence. 

numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

 

Examples: 

>>> np.array([1, 2, 3])

array([1, 2, 3])

>>> np.array([[1, 2],[3, 4]])

array([[1, 2],

   [3, 4]])

>>> c = array( [ [1,2], [3,4] ], dtype=complex )

>>> c

array([[1.+0.j, 2.+0.j], 

   [3. + 0.j, 4. + 0.j]])

>>> a = np.array([1, 2, 3], ndmin=2)

>>> a

array([[1, 2, 3]])

>>> a.shape

(1, 3)

>>> np.array(np.mat('1 2; 3 4'))

array([[1, 2],

   [3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)

matrix([[1, 2],

[3, 4]])

 

When subok is True, and object is a subclass of ndarray (such as matrix type), the returned array retains the subclass type 

3.2 ones and zeros series functions 

Sometimes, we have determined the dimensions of the array and the length of each dimension before creating the array. At this time, we can use some of the built-in functions of numpy to create an ndarray. For example: the function ones creates an array of all 1s, the function zeros creates an array of all 0s, and the function empty creates an array with random contents. By default, the types of arrays created with these functions are float64. If you need to specify the data Type, just need the idle dtype parameter: 

>>> a = np.ones(shape = (2, 3))#The shape of the array can be specified by tuples

>>> a

array([[ 1.,  1.,  1.],

   [ 1.,  1.,  1.]])

>>> a.dtype

dtype('float64')

>>> b = np.zeros(shape = [3, 2], dtype=np.int64)#The shape of the array can also be specified by the list, and the array type is specified here

>>> b

array([[0, 0],

   [0, 0],

   [0, 0]])

>>> b.dtype

dtype('int64')

>>> c = np.empty((4,2))

>>> c

array([[  0.00000000e+000,   0.00000000e+000],

   (6.92806325e-310, 6.92806326e-310),

   (6.92806326e-310, 6.92806326e-310),

   [  0.00000000e+000,   0.00000000e+000]])

 

The above three functions also create three multidimensional arrays with the same shape from the known arrays: ones_like, zeros_like, and empty_like. The usage is as follows: 

 >>> a = [[1,2,3], [3,4,5]]

>>> b = np.zeros_like(a)

>>> b

array([[0, 0, 0],

   [0, 0, 0]])

#The other two functions are similar in usage

 

In addition to the above-mentioned functions for creating arrays, there are several special functions as follows: eye – generate a two-dimensional array with all 1s on the diagonal and identity – generate identity matrix full – generate filled with fixed values The array full_like – generates an array filled with fixed values ​​and the same shape as the given array. In particular, the diagonal position of all 1s of the eye function has a parameter k to determine the usage as follows: 

>>> np.eye(3, k = 0)#k=0, the diagonal of all 1s is the main diagonal

array([[ 1.,  0.,  0.],

   [ 0.,  1.,  0.],

   [ 0.,  0.,  1.]])

>>> np.eye(3, k = 1) #k>0, all 1s move diagonally upwards to the corresponding position

array([[ 0.,  1.,  0.],

   [ 0.,  0.,  1.],

   [ 0.,  0.,  0.]])

>>> np.eye(3, k = -1) #k<0, all 1s move diagonally downward to the corresponding position

array([[ 0.,  0.,  0.],

   [ 1.,  0.,  0.],

   [ 0.,  1.,  0.]])

>>> np.identity(4)

array([[ 1.,  0.,  0.,  0.],

   [ 0.,  1.,  0.,  0.],

   [ 0.,  0.,  1.,  0.],

   [ 0.,  0.,  0.,  1.]])

>>> np.full(shape = (2,2), fill_value = 2)

array([[ 2.,  2.],

   [ 2.,  2.]])

>>> np.full_like([[1,2,3],[3,4,5]], 3)

array([[3, 3, 3],

   [3, 3, 3]])

 

3.3 arange、linspace与logspace 

 The arange function is similar to the range function in python. It creates an array by specifying the initial value, final value, and step size (the default step is 1). The linspace function creates a one-dimensional array by specifying the initial value, final value and the number of elements. The logspace function and Linspace is similar, except that it creates a geometric sequence, and the same is also a one-dimensional array instance: np.arange(0,10,2) 

 array([0, 2, 4, 6, 8])

 np.arange(0,10)

 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

 e.g. linspace (0,10, 20)

 array([  0.,   0.52631579,   1.05263158,   1.57894737,

 2.10526316,   2.63157895,   3.15789474,   3.68421053,

 4.21052632,   4.73684211,   5.26315789,   5.78947368,

 6.31578947,   6.84210526,   7.36842105,   7.89473684,

 8.42105263,   8.94736842,   9.47368421,  10.])

 e.g. logspace (0, 10, 10)

 array([  1.00000000e+00,   1.29154967e+01,   1.66810054e+02,

 2.15443469e + 03, 2.78255940e + 04, 3.59381366e + 05,

 4.64158883e + 06, 5.99484250e + 07, 7.74263683e + 08,

 1.00000000e+10])

  

3.4 fromstring and fromfunction 

 The fromstring function reads data from a string and creates an array. The fromfunction function uses the first parameter as a function to calculate each array element (function object or lambda expression can be used), and the second parameter is an instance of the shape of the array: >> > s1 = "1,2,3,4,5"

 >>> np.fromstring(s1, dtype=np.int64, sep=",")

    array([1, 2, 3, 4, 5])

 >>> s2 = "1.01 2.23 3.53 4.76"

 >>> np.fromstring(s2, dtype=np.float64, sep=" ")

 array([ 1.01,  2.23,  3.53,  4.76])

 >>> def func(i, j):

 ... return (i+1)*(j+1)

 ... 

 >>> np.fromfunction(func, (9,9))

 array([[  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.],

 [  2.,   4.,   6.,   8.,  10.,  12.,  14.,  16.,  18.],

 [  3.,   6.,   9.,  12.,  15.,  18.,  21.,  24.,  27.],

 [  4.,   8.,  12.,  16.,  20.,  24.,  28.,  32.,  36.],

 [  5.,  10.,  15.,  20.,  25.,  30.,  35.,  40.,  45.],

 [  6.,  12.,  18.,  24.,  30.,  36.,  42.,  48.,  54.],

 [  7.,  14.,  21.,  28.,  35.,  42.,  49.,  56.,  63.],

 [  8.,  16.,  24.,  32.,  40.,  48.,  56.,  64.,  72.],

 [  9.,  18.,  27.,  36.,  45.,  54.,  63.,  72.,  81.]])

 >>> np.fromfunction(lambda i,j: i+j, (3,3), dtype = int)

 array([[0, 1, 2],

 [1, 2, 3],

 [2, 3, 4]])

  

In addition to the above two functions, there are several other similar methods to obtain data from the outside and create an ndarray, such as frombuffer, fromfile, and fromiter, which have not been used yet. When used, record in detail 

4 ndarray creates a special two-dimensional array 

ndarray provides some special functions for creating two-dimensional arrays. Matrix in numpy is a subclass after encapsulating the two-dimensional array ndarray. The creation of a two-dimensional array introduced here is still an ndarray object, not a matrix subclass. The creation and operation of the matrix will be described in detail in subsequent notes. For ease of presentation, the matrix is ​​still used this time to represent the created two-dimensional array. 

 The diag function returns the diagonal elements of a matrix, or creates a diagonal matrix. The diagonal is controlled by the parameter k. The diagflat function takes the input as the diagonal element to create a matrix. The diagonal is controlled by the parameter k to generate a tri function. Matrix, the elements below a certain diagonal are all 1, and the rest are all 0. The diagonal is controlled by the parameter k. Tril function inputs a matrix and returns the lower triangular matrix of the matrix. The boundary diagonal of the lower triangle is controlled by the parameter k The triu function is similar to tril, it returns the upper triangular matrix of the matrix. The vander function inputs a one-dimensional array and returns a Vandermonde matrix. #diag usage

 >>> x = np.arange(9).reshape((3,3))

 >>> x

 array([[0, 1, 2],

 [3, 4, 5],

 [6, 7, 8]])

 >>> np.diag(x)

 array([0, 4, 8])

 >>> np.diag(x, k=1)

 array([1, 5])

 >>> np.diag(x, k=-1)

 array([3, 7])

 >>> np.diag (np.diag (x))

 array([[0, 0, 0],

  [0, 4, 0],

  [0, 0, 8]])

  >> np.diag (np.diag (x), k = 1)

  array([[0, 0, 0, 0],

  [0, 0, 4, 0],

  [0, 0, 0, 8],

  [0, 0, 0, 0]])

  #diagflat Usage

  >>np.diagflat([[1,2],[3,4]])

  array([[1, 0, 0, 0],

  [0, 2, 0, 0],

  [0, 0, 3, 0],

      [0, 0, 0, 4]])

  >> e.g. diagflat ([1,2,3], k = -1)

  array([[0, 0, 0, 0],

  [1, 0, 0, 0],

  [0, 2, 0, 0],

  [0, 0, 3, 0]])

  #tri

  >>np.tri(3,4, k=1, dtype=int)  

  array([[1, 1, 0, 0],

  [1, 1, 1, 0],

  [1, 1, 1, 1]])

  >>np.tri(3,4)

  array([[ 1.,  0.,  0.,  0.],

  [ 1.,  1.,  0.,  0.],

  [ 1.,  1.,  1.,  0.]])

  #tril given triu

  >>x = np.arange(12).reshape((3,4))

  >>x

  array([[ 0,  1,  2,  3],

  [ 4,  5,  6,  7],

  [ 8,  9, 10, 11]])

  >>np.tril(x, k=1) 

  array([[ 0,  1,  0,  0],

  [ 4,  5,  6,  0],

  [ 8,  9, 10, 11]])

  >>np.triu(x, k=1) 

  array([[ 0,  1,  2,  3],

  [ 0,  0,  6,  7],

  [ 0,  0,  0, 11]])

  #vander

  >>np.vander([2,3,4,5])

  array([[  8,   4,   2,   1],

  [ 27,   9,   3,   1],

  [ 64,  16,   4,   1],

  [125,  25,   5,   1]])

  >>np.vander([2,3,4,5], N=3)

  array([[ 4,  2,  1],

  [ 9,  3,  1],

  [16,  4,  1],

  [25,  5,  1]])

  

5 ndarray element access 

5.1 One-dimensional array 

For one-dimensional ndarray, you can use python to access the built-in list: integer index, slicing, iteration, etc. 

The ndarray slice is similar to the built-in list slice, in the form: 

beg: start index 

end: end index (not including this element) 

step: Interval need to pay attention to: 

 beg can be empty, which means starting from index 0; end can also be empty, which means reaching the end of the index (including the last element); step is empty, which means the interval is 1; negative index: the index of the last element is- 1. Subtract 1 from this step forward. Negative step: get elements from back to front >>> x = np.arange(16)*4

  >>> x

  array([ 0,  4,  8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60])

  >>> x[11]

  44

  >>> x[4:9]

  array([16, 20, 24, 28, 32])

  >>> x[:10:3]

  array([ 0, 12, 24, 36])

  >>> x[0:13:2]

  array([ 0,  8, 16, 24, 32, 40, 48])

  >>> x[::-1]#Reverse array

  array([60, 56, 52, 48, 44, 40, 36, 32, 28, 24, 20, 16, 12,  8,  4,  0])

  >>> print [val for val in x]#iterate element

  [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60]

  

Special attention is that the elements in the array returned by the slice in the ndarray are the indexes of the original array elements. Modifying the returned array elements will affect the value of the original array 

     >>> x[:-1]

     array([ 0,  5, 10, 15, 20, 25, 30, 35, 40])

     >>> y = x[::-1]

     >>> y

     array([45, 40, 35, 30, 25, 20, 15, 10,  5,  0])

     >>> y[0] = 100#Modify the value of the first element of y

     >>> y

     array([100,  40,  35,  30,  25,  20,  15,  10,   5,   0])

     >>> x #x[-1] is also modified (essentially an element)

     array([  0,   5,  10,  15,  20,  25,  30,  35,  40, 100])

 

In addition to the above method of accessing elements similar to the list, ndarray has a way to specify the index of the element to be obtained from the ndarray through a list, for example: 

     >>> x = np.arange(10)*5

     >>> x

     array([ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45])

     >>> x[[0, 2, 4, 5, 9]]# specify to get the elements with index 0, 2, 4, 5, 9

     array([ 0, 10, 20, 25, 45])

 

5.2 Multidimensional array 

In a multidimensional ndarray, each dimension is called an axis. In the ndarray, the axis axis is very important. Many operations on the ndarray object are based on the axis. For example, sum, mean, etc. will have an axis parameter (for certain operations on this axis axis), which will be detailed later Introduction. For multidimensional arrays, because each axis has an index, these indexes are separated by commas, for example: 

     >>> x = np.arange(0, 100, 5).reshape(4, 5)

     >>> x

     array([[ 0,  5, 10, 15, 20],

     [25, 30, 35, 40, 45],

     [50, 55, 60, 65, 70],

     [75, 80, 85, 90, 95]])

     >>> x[1,2] #The first row, the second column

     35

     >>> x[1:4, 3]#All elements in column 3 from row 1 to row 3

     array([40, 65, 90])

     >>> x[:, 4] #All 4th column elements in all rows

     array([20, 45, 70, 95])

     >>> x[0:3, :]#Elements of all columns from row 0 to row 3

     array([[ 0,  5, 10, 15, 20],

     [25, 30, 35, 40, 45],

     [50, 55, 60, 65, 70]])

 

have to be aware of is: 

 When the provided index is less than the number of axes, the missing index represents the entire slice (only the axis behind it is missing). When the provided index is:, it also means that the entire slice can be used... instead of several consecutive: index >>> x[ 1:3]#Missing the second axis

  array([[25, 30, 35, 40, 45],

  [50, 55, 60, 65, 70]])

  >>> x[:, 0:4] #The first axis is:

  array([[ 0,  5, 10, 15],

  [25, 30, 35, 40],

  [50, 55, 60, 65],

  [75, 80, 85, 90]])

  >>> x[..., 0:4]#... represents the index of the first axis

  array([[ 0,  5, 10, 15],

  [25, 30, 35, 40],

  [50, 55, 60, 65],

  [75, 80, 85, 90]])

  

Multidimensional array iteration 

You can iterate each element in the array using the flat attribute of ndarray 

>>> for item in x.flat:

... print item,

...

0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95

 

[Original link (https://blog.csdn.net/scorpion_zs/article/details/52526310)

Guess you like

Origin blog.csdn.net/u013946150/article/details/113057701