Python scientific computing -NumPy basis (2)

  • Mathematical Functions
  • Array indexing and slicing

Mathematical Functions

Using Python comes with the operator, you can do the arithmetic in mathematics, as well as take over, rounding, power of computing. After the introduction comes math module, which also contains an absolute value, a number of factorial, square root and other common mathematical functions. However, these functions are still relatively basic. If you want to complete some of the more complex mathematical calculations, it will become stretched up.

(1) trigonometric
numpy.sin (x): trigonometric sine.
numpy.cos (x): trigonometric cosine.
numpy.tan (x): triangle tangent.
numpy.arcsin (x): Triangle asin.
numpy.arccos (x): inverse cosine triangle.
numpy.arctan (x): trigonometric arc tangent.
numpy.hypot (x1, x2): find the hypotenuse of a right triangle.
numpy.degrees (x): convert radians to degrees.
numpy.radians (x): degrees to radians.
numpy.deg2rad (x): degrees to radians.
numpy.rad2deg (x): convert radians to degrees.

(2) hyperbolic functions
numpy.sinh (x): hyperbolic sine.
numpy.cosh (x): hyperbolic cosine.
numpy.tanh (x): Hyperbolic tangent.
numpy.arcsinh (x): inverse hyperbolic sine.
numpy.arccosh (x): inverse hyperbolic cosine.
numpy.arctanh (x): inverse hyperbolic tangent.

(3) rounding off
rounding off, also known as digital rounding means before performing a specific digital operation, the same number of bits is determined according to certain rules, and then the process of discarding the excess mantissa some later figures. For example, we often hear, "5 into 4 round" on belongs to a rounding off of.
numpy.around (a): the average number of decimal places given.
numpy.round_ (a): the array rounded to the given number of decimal places.
numpy.rint (x): rounding to the nearest integer.
numpy.fix (x, y): 0 to round to the nearest integer.
numpy.floor (x): returns to the bottom input.
numpy.ceil (x): Returns the upper limit input.
numpy.trunc (x): Returns the input cutoff.

a = np.random.randn(5)  # 生成 5 个随机数
a  # 输出 a 的值
> array([-0.36063527,  0.48682976, -0.4143421 ,  0.21499006,  0.25709575])

np.around(a)
> array([-0.,  0., -0.,  0.,  0.])

np.rint(a)
> array([-0.,  0., -0.,  0.,  0.])

np.fix(a)
> array([-0.,  0., -0.,  0.,  0.])

(4) a sum, product, difference
numpy.prod (a, axis, dtype, keepdims): returns the product of the specified array element axis.
numpy.sum (a, axis, dtype, keepdims): Returns the sum of array element axis.
numpy.nanprod (a, axis, dtype, keepdims): Returns the specified axis of the array elements of the product, will be treated as a NaN.
numpy.nansum (a, axis, dtype, keepdims): Returns the sum of array element axis, of NaN treated as 0.
numpy.cumprod (a, axis, dtype) : returns the cumulative product of elements along a given axis.
numpy.cumsum (a, axis, dtype) : returns the cumulative sum of the elements along a given axis.
numpy.nancumprod (a, axis, dtype) : returns the cumulative product of elements along a given axis will NaN regarded as 1.
numpy.nancumsum (a, axis, dtype) : returns the cumulative sum of the elements along a given axis, the 0 NaN considered.
numpy.diff (a, n, axis) : calculated along a specified axis of n discrete differential.
numpy.ediff1d (ary, to_end, to_begin) : the difference between successive elements of the array.
numpy.gradient (f): Returns a gradient of N-dimensional arrays.
numpy.cross (a, b, axisa, axisb, axisc, axis): returns the cross product of two (arrays) vector.
numpy.trapz (y, x, dx, axis): composite trapezoidal rule integration along the given axis.

(5) exponential and logarithmic
numpy.exp (x): index calculating all elements of the input array.
numpy.log (x): natural logarithm.
numpy.log10 (x): calculated common logarithm.
numpy.log2 (x): calculated for binary numbers.

(6) arithmetic
numpy.add (x1, x2): the corresponding elements are added.
numpy.reciprocal (x): a reciprocal 1 / x.
numpy.negative (x): find the corresponding negative.
numpy.multiply (x1, x2): Solving multiplication.
numpy.divide (x1, x2): division x1 / x2.
numpy.power (x1, x2): similar x1 ^ x2.
numpy.subtract (x1, x2): subtraction.
numpy.fmod (x1, x2): Returns the remainder of the division element.
numpy.mod (x1, x2): returns the remainder.
numpy.modf (x1): returns the integer part and a fractional array.
numpy.remainder (x1, x2): Returns the division remainder.

a1 = np.random.randint(0, 10, 5)  # 生成 5 个从 0-10 的随机整数
a2 = np.random.randint(0, 10, 5)
a1, a2  # 输出 a1, a2
> (array([5, 0, 8, 2, 0]), array([7, 8, 7, 1, 4]))

np.add(a1, a2)
> array([12,  8, 15,  3,  4])

np.negative(a1)
> array([-5,  0, -8, -2,  0])

np.multiply(a1, a2)
> array([35,  0, 56,  2,  0])

np.divide(a1, a2)
> np.divide(a1, a2)

np.power(a1, a2)
> array([  78125,       0, 2097152,       2,       0])

(7) and the matrix vector product
numpy.dot (a, b): Solving the dot product of two arrays.
numpy.vdot (a, b): Solution dot product of two vectors.
numpy.inner (a, b): Solution inner product of two arrays.
numpy.outer (a, b): Solution outer product of two vectors.
numpy.matmul (a, b): solving the matrix product of two arrays.
numpy.tensordot (a, b): Product Solution tensors.
numpy.kron (a, b): calculated Kronecker product.

numpy.angle(z, deg): Returns the angle complex parameters.
numpy.real(val): Returns the real part of the array elements.
numpy.imag(val): Returns the imaginary part of the array elements.
numpy.conj(x): Return by way conjugate complex elements.
numpy.convolve(a, v, mode): Returns linear convolution.
numpy.sqrt(x): Square root.
numpy.cbrt(x): Cube root.
numpy.square(x):square.
numpy.absolute(x): Absolute value, which can be solved complex.
numpy.fabs(x): Absolute.
numpy.sign(x): Sign function.
numpy.maximum(x1, x2): Maximum.
numpy.minimum(x1, x2): Minimum.
numpy.nan_to_num(x): Replace with a NaN 0.
numpy.interp(x, xp, fp, left, right, period): Linear interpolation.

(8) algebra
numpy.linalg.cholesky(a): Cholesky decomposition.
numpy.linalg.qr(a ,mode): Calculation of matrix QR factorization.
numpy.linalg.svd(a ,full_matrices,compute_uv): Singular value decomposition.
numpy.linalg.eig(a): Calculating the square array of eigenvalues and right eigenvectors.
numpy.linalg.eigh(a, UPLO): Returns or Hermitian symmetric matrix of eigenvalues and eigenvectors.
numpy.linalg.eigvals(a): Calculating eigenvalues.
numpy.linalg.eigvalsh(a, UPLO): Characteristic value calculating Hermitian or real symmetric matrix.
numpy.linalg.norm(x ,ord,axis,keepdims): Calculating matrix or vector norm.
numpy.linalg.cond(x ,p): Compute the matrix condition number.
numpy.linalg.det(a): Determinant calculation array.
numpy.linalg.matrix_rank(M ,tol): Using singular value decomposition method returns rank.
numpy.linalg.slogdet(a): A natural number of symbols and calculating the determinant of the array.
numpy.trace(a ,offset,axis1,axis2,dtype,out): Returns the sum of the diagonal of the array.
numpy.linalg.solve(a, b): Linear matrix equation or linear scalar equations.
numpy.linalg.tensorsolve(a, b ,axes): Tensor to solve the equation x = B AX
numpy.linalg.lstsq(a, b ,rcond): returns a least squares solution to the linear matrix equation.
numpy.linalg.inv(a): Calculate the inverse matrix.
numpy.linalg.pinv(a ,rcond): Calculating matrix (Moore-Penrose) pseudo-inverse.
numpy.linalg.tensorinv(a ,ind): Calculating an inverse N-dimensional array.

Array indexing and slicing

Array index

(1)
a = np.arange(10)  # 生成 0-9
a[1] # 获取索引值为 1 的数据
a[[1, 2, 3]] # 分别获取索引值为 1,2,3 的数据

(2)
a = np.arange(20).reshape(4, 5)
a[1, 2] # 获取第 2 行,第 3 列的数据


# Python 中 list 索引 2 维数据的方法正确的做法是a[1][2]
a = a.tolist()
a[1][2]


a = np.arange(20).reshape(4, 5)
> array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
       
a[[1, 2], [3, 4]]
> array([ 8, 14])
# 这里需要注意索引的对应关系。我们实际获取的是 [1, 3],也就是第 2 行和第 4 列对于的值 8。以及 [2, 4],也就是第 3 行和第 5 列对应的值 14。

(3)
a = np.arange(30).reshape(2, 5, 3)
> array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11],
        [12, 13, 14]],

       [[15, 16, 17],
        [18, 19, 20],
        [21, 22, 23],
        [24, 25, 26],
        [27, 28, 29]]])
 
 a[[0, 1], [1, 2], [1, 2]]
 > array([ 4, 23])

Array slice

Ndarray[start:stop:step]: [start:stop:step]Representing [起始索引:截至索引:步长].

For one-dimensional array:

 a = np.arange(10)
 a[:,5]
 a[5:10]
 a[0:10:2]

For multidimensional arrays, we only need to use a comma- ,separate the different dimensions can be:

a = np.arange(20).reshape(4,5)
a[0:3,2:4] # 先取第 3,4 列,再取第 1,2,3 行
a[:,::2]  # 按步长为 2 取所有列和所有行的数据。

Sequence

numpy.sort(a, axis=-1, kind='quicksort', order=None)
a: Array.
axis: To sort the shaft. If it is None, then sort the array before paving. The default value is -1, the last ordering along one axis.
kind: {'quicksort','mergesort','heapsort'}, Sorting algorithms. The default value quicksort.

a = np.random.rand(20).reshape(4,5)
array([[0.4067026 , 0.02296533, 0.06435257, 0.99077083, 0.46672518],
       [0.73621431, 0.3910597 , 0.72614588, 0.55235663, 0.75587185],
       [0.38226065, 0.42122671, 0.02584968, 0.38518907, 0.62174531],
       [0.22214217, 0.00723674, 0.29625144, 0.85690794, 0.58018676]])

np.sort(a)
array([[0.02296533, 0.06435257, 0.4067026 , 0.46672518, 0.99077083],
       [0.3910597 , 0.55235663, 0.72614588, 0.73621431, 0.75587185],
       [0.02584968, 0.38226065, 0.38518907, 0.42122671, 0.62174531],
       [0.00723674, 0.22214217, 0.29625144, 0.58018676, 0.85690794]])

numpy.lexsort(keys ,axis): Indirect sorted using a plurality of keys.
numpy.argsort(a ,axis,kind,order): Along a given axis perform an indirect sort.
numpy.msort(a): A shaft along the first sort.
numpy.sort_complex(a): Sort against plural.

Search and counting

argmax(a ,axis,out): Returns the maximum value specified in the array axis index .
nanargmax(a ,axis): Returns the index of the maximum value specified in the array axis, ignoring NaN.
argmin(a ,axis,out): Returns the index of the minimum specified in the array axis.
nanargmin(a ,axis): Returns the index of the minimum specified in the array axis, ignoring NaN.
argwhere(a): Returns the array index of nonzero elements, grouped elements.
nonzero(a): Returns the array index of nonzero elements.
flatnonzero(a): Returns the index of the array of nonzero elements, and paved.
where(条件,x,y): According to specified conditions, from the specified row, column returns the element.
searchsorted(a,v ,side,sorter): Find the elements to be inserted in order to maintain the index.
extract(condition,arr): Returns an array of elements that meet certain criteria.
count_nonzero(a): Calculate the number of nonzero elements in the array.

a = np.random.randint(0, 10, 20)
array([8, 7, 3, 8, 0, 9, 3, 0, 5, 6, 6, 9, 4, 4, 5, 4, 5, 3, 5, 2])

np.argmax(a)
5
np.argmin(a)
4
np.nonzero(a)
(array([ 0,  1,  2,  3,  5,  6,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
        19]),)

np.count_nonzero(a)
18

source

Published 33 original articles · won praise 1 · views 1237

Guess you like

Origin blog.csdn.net/weixin_44783002/article/details/104718186