Home > Article > Backend Development > Basic learning of numpy in python and performing array and vector calculations
Preface
In python, sometimes we use arrays to operate data, which can greatly improve the data processing efficiency. Similar to R's vectorization operation, it is the trend of data operation. For simplicity, array and vector calculations can be performed using the numpy module in python.
Let’s take a look at a simple example
import numpy as np data=np.array([2,5,6,8,3]) #构造一个简单的数组 print(data)
Result:
[2 5 6 8 3]
data1=np.array([[2,5,6,8,3],np.arange(5)]) #构建一个二维数组 print(data1)
Result:
[[2 5 6 8 3] [0 1 2 3 4]]
We can also view the dimensions and data format of the array through the shape and dtype methods
print(data.shape) print(data.dtype) print(data1.shape) print(data1.dtype)
Result:
(5,) int32 (2, 5) int32
It can be seen that data is a one-dimensional array, with 5 elements in each group. The data type is 32-bit int type
data1 is a two-dimensional array, each group has 5 elements, the data type is 32-bit int type
A better way to distinguish is to look at the print In the result, the number and position of the square brackets can indicate the dimensions of the array. One layer of square brackets represents a dimension.
Other array attribute methods include:
array.ndim
The dimension of the array, the result of a one-dimensional array is 1, and the result of a two-dimensional array is 1 The print result is 2
array.size
The number of elements in the array
array.itemsiz
The byte size of each element in the array
Next let’s learn about the data types in the array:
Basic data types in NumPy
Name | Description |
bool | Boolean type (True or False) stored in one byte |
inti | An integer whose size is determined by the platform (usually int32 or int64) |
int8 | One Byte size, -128 to 127 |
int16 | Integer, -32768 to 32767 |
Integer, -2 ** 31 to 2 ** 32 -1 | |
Integer, -2 ** 63 to 2 ** 63 - 1 | |
Unsigned integer, 0 to 255 | |
Unsigned integer, 0 to 255 65535 | |
Unsigned integer, 0 to 2 ** 32 - 1 | |
Unsigned integer, 0 to 2 ** 64 - 1 | |
Half-precision floating point number: 16 bits, 1 bit for sign, 5 bits for exponent, Precision 10 digits | |
Single precision floating point number: 32 digits, 1 sign, 8 exponent, 23 digits precision | |
Double precision floating point number: 64 bits, 1 bit for sign, 11 bits for exponent, 52 bits for precision | |
Complex numbers, use two 32-bit floating point numbers to represent the real part and imaginary part respectively | |
Complex numbers, use two 64-bit floating point numbers respectively Points represent real and imaginary parts |