Python scientific computing-NumPy getting started, pythonnumpy
Preface
NumPy is a fast mathematical library used by Python to process large matrices. It allows you to perform vector and matrix operations in Python, and many underlying functions are written in C. You will get the running speed that cannot be achieved in normal Python. This is because the data types of each element in the matrix are the same, which reduces the type detection during the operation.
Matrix Basics
In the numpy package, we use arrays to represent vectors, matrices, and high-level data structures. They are composed of arrays, represented by an array in one dimension, and represented by arrays in two dimensions.
Create
# coding: utf-8import numpy as npa = np.array([ [1.73, 1.68, 1.71, 4], [1, 2, 3, 4], [1, 2, 3, 4]])print type(a) # <type 'numpy.ndarray'>
Ndarray (N-dimen1_array object) is an N-dimensional array. In this example, a two-dimensional array with three rows and four columns is displayed.
Shape
The array size can be obtained through its shape attribute:
print a.shape # (3L,4L)
The number of elements in the array can be obtained through ndarray. size:
print a.size # 12
Using the dtype attribute of ndarray, we can obtain the type of array elements:
print a.dtype # float64
You can use shape to reset the shape of the matrix or use the reshape method to create a new array that has changed the size. The shape of the original array remains unchanged:
A. shape = 4, 3b =. reshape (2, 6) # although the shape of B is new, a and B are in the shared data storage memory area, if B [0] [1] = 8, then a [0] [1] will also be 8
Array generation
Yesnp.arange To create an array. The parameters are similar to range:
x = np.arange(0, 10, 1) # arguments: start, stop, step
You can also use np. linspace to create an equal difference sequence:
X = np. linspace (1, 10, 5) # arguments: start, stop, number of num elements #[1. 3.25 5.5 7.75 10.] # np. logspace is used to create an proportional Sequence
Matrix Operations
The calculation directly participates in the operator, and the operator priority remains unchanged:
a = np.random.rand(5, 5)b = np.random.rand(5, 5)print a + bprint a - bprint a * bprint a / bprint a ** 2print a < bprint a > b
In additiondot() Other operations are unit operations.
Np_arr = np. array ([2, 3, 34, 5, 5]) print np. mean (np_arr) # average print np. median (np_arr) # median print np. effeccoef (a [0], a [1]) # determines whether data in the two axes is correlated with print np. std (np_arr) # Standard Deviation
Data Extraction
Slice index Syntax:M[lower:upper:step]
A = np. array ([, 5]) a [] # array ([2, 3]) # When you assign values to slices, the original array is modified to a [] = [-2,-3] # array ([1,-2,-3, 4, 5]) B = np. random. rand (5, 5) B [,] # extract 1 ~ 4 rows, 1 ~ 4 columns B> 0.1 # array ([False,...]) # therefore, extraction can be used. This feature uses Boolean shielding. B [B> 0.1] # The where () function is another useful method, when you need to retrieve array elements with specific conditions. You only need to pass a condition to it. It returns the list of elements that meet the condition. C = np. where (B> 0.1)
Matrix Operations
NumPy is different from Matlab. By default, matrix operations are not used for multi-dimensional array operations. If you want to perform matrix operations on arrays, you can call the corresponding functions.
Matrix object
The numpy Library provides the matrix class. matrix objects are created using the matrix class. Their addition, subtraction, multiplication, division operations are calculated using the matrix method by default. Therefore, their usage is similar to that of matlab. However, because NumPy contains both ndarray and matrix objects, it is easy for users to mix them. This violates Python's principle of "explicit superiority over implicit", so it is not recommended to use matrix in more complex programs.
>>> a = np.matrix([[1,2,3],[5,5,6],[7,9,9]])>>> a*a**-1matrix([[ 1.00000000e+00, 1.66533454e-16, -8.32667268e-17], [ -2.77555756e-16, 1.00000000e+00, -2.77555756e-17], [ 1.66533454e-16, 5.55111512e-17, 1.00000000e+00]])
You can usem = np.matrix(a)For conversion, use m. T to obtain m's transpose matrix.
Matrix Inversion
m.I * m=> matrix([[ 1.00000000e+00+0.j, 4.44089210e-16+0.j], [ 0.00000000e+00+0.j, 1.00000000e+00+0.j]])
Shallow copy and deep copy
In order to achieve high performance, assignment in Python often does not copy the underlying object, which is called a shortest copy. Use copy for deep copy:
b = copy(a)
Traverse array elements
In general, we want to avoid traversing array elements as much as possible. Because iterations are much slower than vector operations. But sometimes iteration is inevitable. In this case, using Python for is the most convenient:
v = np.array([1,2,3,4])for element in v: print(element)M = np.array([[1,2], [3,4]])for row in M: print("row", row) for element in row: print(element)
Summary
The above is all about NumPy in Python scientific computing. I hope this article will help you in your study or work. If you have any questions, please leave a message.