numpy Quick Start Tutorial

1,906 Views
No Comments

Total 3927 characters, estimated reading time: 10 minutes.

Getting Started with Python Library Numpy

NumPy is the basic package for scientific computing in Python. It is a Python library that provides multi-dimensional array objects, various derived objects (such as mask arrays and matrices), and various routines for fast operations on arrays, including mathematics, logic, shape operations, sorting, selection, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation, and more.

At the heart of numpy is the ndarray object, which is a multidimensional array.


install

Install with pip

pip install numpy

official website download

Release NumPy v1.26


Basic use

Multidimensional Array Concepts

In numpy,Dimension (dimensions) be called Axes.

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

In the above array, there are two axes, that is, a two-dimensional array (two-dimensional space). The first axis has three elements, namely [ 0 1 2 3 4 ],[ 5 6 7 8 9 ] and [ 10 11 12 13 14 ]The length is 3. The second axis has five elements, that is, a length of 5.

Create an array

The class of numpy arrays is ndarray, which is different from array.array in the Python standard library.

The following is an example of creating a numpy array:

# 先导入numpy,别称为np
import numpy as np
# 生成一个5x3的二维数组a
a = np.arange(15).reshape(5,3)
print(a)
# 将会输出:
# [[ 0  1  2]
# [ 3  4  5]
# [ 6  7  8]
# [ 9 10 11]
# [12 13 14]]

In addition, the ndarray has a variety of properties, as follows:

# 数组的维数
print(a.ndim)
# 结果:2
# 表示数组为2维空间

# 数组的形状
print(a.shape)
# 结果:(5,3)
# 表示数组为5x3的二维数组

# 数组的类型(data type)
print(a.dtype)

# 数组中每个元素的大小(bit)
print(a.itemsize)

# 输出数组在内存中的真实数据
# 通常不会用到该属性
print(a.data)

Similarly, you can create numpy arrays from lists in the python standard library:

# 调用np.array()方法即可把列表转换成数组
a = np.array([1,2,3])
# 同样浮点型也适用
a = np.array([1.2,2.4,1.8])

# 还可以转换成多维数组
b = np.array([(1.5, 2, 3), (4, 5, 6)])
print(b)
# 结果:
# [[1.5 2.  3. ]
#  [4.  5.  6. ]]
b = np.array([[1, 2], [1, 2]], dtype=complex)
# complex是复数类型

For efficiency, numpy also provides methods for creating empty arrays:

# 创建全为0的2x3的二维数组
np.zeros((2,3))
# 创建全为1的2x3x4的三维数组
np.ones((2,3,4))
# 创建空数组(数据值取决于内存,即随机)
np.empty((2,3))

Let's review the first example in this paragraph, where the arange method can generate an increasing or decreasing sequence:

# np.arange(start,stop,step)
#           起始   结束  步进
# 创建一个从[0,5)的一个一维数组
a = np.arange(5)
print(a)
# 结果:[0 1 2 3 4]

# 创建一个从[10,30),步进为5的一维数组
a = np.arange(10,30,5)
# 结果:[10 15 20 25]

# 也可以是递减的
a = np.arange(30,10,-5)
# 结果:[30 25 20 15]

If you want to generate a sequence with decimals, you recommend use the linspace method, which generates an equally spaced sequence:

# np.linspace(start,stop,num)
#             起始   结束  数的个数
# 把[0,5]等间距的分成6个数
d = np.linspace(0, 5, 6)
print(d)
# 结果:[0. 1. 2. 3. 4. 5.]
# 注意:间距=(stop-start)/(num-1)

# 计算sin(x)在[0,2π]区间内等间距的10个点的数值
from numpy import pi
x = np.linspace(0, 2 * np.pi, 10)
f = np.sin(x)
print(f)
# 结果:[ 0.00000000e+00  6.42787610e-01  9.84807753e-01  8.66025404e-01
#        3.42020143e-01 -3.42020143e-01 -8.66025404e-01 -9.84807753e-01
#       -6.42787610e-01 -2.44929360e-16]

These sequences can also be used reshape() method to reassign to a new multidimensional array:

# 创建一个1~10的5x2的二维数组
a = np.arange(1,11).reshape(5,2)

Array operations (basic operations)

Mr. into two ndarray variables:

a = np.array([10, 10, 10])
# [10,10,10]
b = np.arange(3)
# [0 ,1 ,2]

Do the following operations:

# a数组减去b数组
a - b
# 得到:[10,9,8]

# b数组的2次幂
b**2
# 得到:[0,1,4]

# b数组是否小于1
b < 1
# 得到:[True, False, False]

The following is the operation of a multidimensional array:

A = np.array([[1,1],
              [0,1]])
B = np.array([[2,0],
              [3,4]])

# 矩阵对应元素相乘
A * B
# 得到:
# [[2 0]
#  [0 4]]

# 以下运算才是矩阵的相乘(线性代数)
A @ B
# 得到:
# [[5 4]
#  [3 4]]
A.dot(B)
# 以上也能实现矩阵相乘 等同于 A@B

# 一个数乘以矩阵
3 * B
# 得到:
# [[ 6  0]
#  [ 9 12]]

A *= 3
# 相当于 A = A * 3
B += A
# 相当于 B = B + A

Other common operations:

# 复数运算
np.exp(B * 2j)
# j代表复数

# 求和(数组内所有元素的和)
np.sum(B)

# 求最小元素
np.min(B)

# 求最大元素
np.max(B)

Indexing and slicing

one-dimensional array

For one-dimensional arrays, it is very similar to Python's own list operation:

# 产生10个元素的数组
a = np.arange(10)
# [0 1 2 3 4 5 6 7 8 9]
# 索引为3的元素表示为
a[3]     # 3
# 注意索引从0~9共十个数
# 还可以进行切片 输出索引2,3的数
a[2:4]   # [2 3]
# 也可以设置步长
# 如下可以实现逆序该数组
a[::-1]  # [9 8 7 6 5 4 3 2 1 0]

# 遍历每一个元素
for t in a:
    print(t)

multidimensional array

In a multidimensional array, there is an index for each axis.

The following is an example of a two-dimensional array operation:

# [[ 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 = np.arange(30).reshape(5,6)
# 取第3行第4个元素
# 索引依次为2,3
a[2,3]    # 15
# 当然也能进行切片
# 第一个索引表明只保留第2,3行
# 第二个索引表明取全部元素
a[1:3,:]  # [[12 13 14 15 16 17]
          #  [18 19 20 21 22 23]]

For an N-dimensional array, similar to a two-dimensional array,a[1,2,3, ...], there are N indexes that can be used.

Shape Operations

The most common method is still reshape() method, an example is as follows:

# 3行4列的矩阵
a = np.arange(12).reshape(3, 4)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# 改变成6行2列的矩阵
a = a.reshape(6, 2)
# [[ 0  1]
#  [ 2  3]
#  [ 4  5]
#  [ 6  7]
#  [ 8  9]
#  [10 11]]
# 改变成2x3x2的三维数组
a = a.reshape(2, 3, 2)
# [[[ 0  1]
#   [ 2  3]
#   [ 4  5]]

#  [[ 6  7]
#   [ 8  9]
#   [10 11]]]

can also be used ravel() method expands a multidimensional array into a 1-dimensional array, a list:

# 2x3x2的三维数组
a = np.arange(12).reshape(2, 3, 2)
# 展开为一维数组
a = a.ravel()
# [ 0  1  2  3  4  5  6  7  8  9 10 11]

There's another one in the ndarray T property, you can get the transpose of the matrix:

# 3行4列的矩阵
a = np.arange(12).reshape(3, 4)
# 输出a的转置
print(a.T)
# [[ 0  4  8]
#  [ 1  5  9]
#  [ 2  6 10]
#  [ 3  7 11]]
# 变成4行3列的了,元素也转置了

compared reshape() can only return a modified array,resize() Method can directly modify the current array without accepting the return value, as shown in the following example:

# 3行4列的矩阵
a = np.arange(12).reshape(3, 4)
# 以下两句代码的作用是相同的
a = a.reshape(4, 3)
a.resize(4, 3)
# 打印a
print(a)

Splice and Split Arrays

Splicing

Vertical Splicing

np.vstack()

Horizontal Splicing

np.hstack()

Separation

Vertical separation

np.vsplit()

Horizontal separation

np.hsplit()

array copy

Similar to objects in Python, the following code does not copy arrays directly:

a = np.arange(12).reshape(3, 4)
b = a
# a和b实际是相同的
print(a is bs)
# True

shallow copy

The shallow copy does not copy the elements inside, that is, the two variables share the elements inside, as in the following example:

a = np.arange(12).reshape(3, 4)
# b是a的浅拷贝
b = a.view()
# b中的元素不是自己的
print(b.flags.owndata)
# False
# b改变形状并不会影响a
b.resize((4,3))
print(b)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]
print(a)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# 但是改变b中的元素会影响a的元素
b[0, 0] = 100
print(a)
# [[100   1   2   3]
#  [  4   5   6   7]
#  [  8   9  10  11]]

Deep Copy

Use copy() method can completely copy all the elements inside, making them two completely independent variables:

a = np.arange(12).reshape(3, 4)
b = a.copy()
# 此时无论b中元素怎么改变都不会影响a的任何元素

END
 0
Comment(No Comments)
Captcha