Numpy array and matrix operations (1)

Numpy arrays and their operations

create array

An array is a contiguous memory space used to store several data, where the elements are generally of the same type.

>>> import numpy as np
>>> np.array([1,2,3,4,5]) # 把列表转换为数组
array([1, 2, 3, 4, 5])
>>> np.array((1,2,3,4,5)) # 把元组转换为数组
array([1, 2, 3, 4, 5])
>>> np.array(range(5)) # 把range对象转换为数组
array([0, 1, 2, 3, 4])
>>> np.array([[1,2,3],[4,5,6]]) # 二维数组
array([[1, 2, 3],
       [4, 5, 6]])
>>> np.arange(8) # 类似于内置函数range()
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.arange(1,10,2) # 1-10 步长为2
array([1, 3, 5, 7, 9])
>>> np.linspace(0,10,11) # 等差数组,包含11个数
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
>>> np.linspace(0,10,11,endpoint=False) # 不包含终点
array([0.        , 0.90909091, 1.81818182, 2.72727273, 3.63636364,
       4.54545455, 5.45454545, 6.36363636, 7.27272727, 8.18181818,
       9.09090909])
>>> np.logspace(0,100,10) # 相当于10**np.linspace(0,100,10)
array([1.00000000e+000, 1.29154967e+011, 1.66810054e+022, 2.15443469e+033,
       2.78255940e+044, 3.59381366e+055, 4.64158883e+066, 5.99484250e+077,
       7.74263683e+088, 1.00000000e+100])
>>> np.logspace(1,6,5,base=2) # 相当于2**np.linspace(1,6,5)
array([ 2.        ,  4.75682846, 11.3137085 , 26.90868529, 64.        ])
>>> np.zeros(3) # 全0一维数组
array([0., 0., 0.])
>>> np.ones(3) # 全1一维数组
array([1., 1., 1.])
>>> np.zeros((3,3)) # 全0二维数组,3行3列
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
>>> np.zeros((3,1)) # 全0二维数组,3行1列
array([[0.],
       [0.],
       [0.]])
>>> np.zeros((1,3)) # 全0二维数组,1行3列
array([[0., 0., 0.]])
>>> np.ones((3,3)) # 全1二维数组
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
>>> np.ones((1,3)) # 全1二维数组
array([[1., 1., 1.]])
>>> np.identity(3) # 单位矩阵
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
>>> np.identity(2)
array([[1., 0.],
       [0., 1.]])
>>> np.empty((3,3)) # 空数组,只申请空间,不初始化
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
>>> np.hamming(20) # Hamming窗口
array([0.08      , 0.10492407, 0.17699537, 0.28840385, 0.42707668,
       0.5779865 , 0.7247799 , 0.85154952, 0.94455793, 0.9937262 ,
       0.9937262 , 0.94455793, 0.85154952, 0.7247799 , 0.5779865 ,
       0.42707668, 0.28840385, 0.17699537, 0.10492407, 0.08      ])
>>> np.blackman(10) # Blackman窗口
array([-1.38777878e-17,  5.08696327e-02,  2.58000502e-01,  6.30000000e-01,
        9.51129866e-01,  9.51129866e-01,  6.30000000e-01,  2.58000502e-01,
        5.08696327e-02, -1.38777878e-17])
>>> np.kaiser(12,5) # Kaiser窗口
array([0.03671089, 0.16199525, 0.36683806, 0.61609304, 0.84458838,
       0.98167828, 0.98167828, 0.84458838, 0.61609304, 0.36683806,
       0.16199525, 0.03671089])
>>> np.random.randint(0,50,5) # 随机数组,5个0到50之间的数字
array([30, 45,  3, 14, 39])
>>> np.random.randint(0,50,(3,5)) # 3行5列
array([[14, 17, 35, 17, 18],
       [31, 43, 16, 16,  5],
       [24, 32,  7, 33, 46]])
>>> np.random.rand(10) # 10个介于[0,1)的随机数
array([0.11167747, 0.40292433, 0.51850811, 0.04377307, 0.11010654,
       0.67654253, 0.9580839 , 0.49403792, 0.90047855, 0.45184538])
>>> np.random.standard_normal(5)# 从标准正态分布中随机采样5个数字
array([-0.77732921, -0.15935702, -0.86469795, -0.67452421,  1.36960344])
>>> np.random.standard_normal(size=(3,4,2)) # 3页4行2列
array([[[ 0.33062086, -0.62089866],
        [-0.75709293, -0.60898432],
        [-1.19973726, -0.71412146],
        [-1.28146037, -0.7100706 ]],

       [[ 1.47959987,  0.51330101],
        [-0.2683062 , -1.10700428],
        [ 1.38848378,  0.0148741 ],
        [ 0.73343418, -1.00783892]],

       [[-0.2872382 ,  0.81962319],
        [-0.52615132,  1.15154691],
        [-1.42739936, -0.71372472],
        [-1.15310821,  0.60050732]]])
>>> np.diag([1,2,3,4]) # 对角矩阵
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])

Tests whether corresponding elements of two arrays are close enough

Numpy provides isclose() and allclose() functions to test whether the elements at corresponding positions in two arrays are equal within the allowable error range, and can receive absolute error parameters and relative error parameters. The isclose() function is used to test whether each pair of elements is equal and returns a list containing several True/False. The allclose() function is used to test whether all elements at corresponding positions are equal and returns a single True or False.

>>> import numpy as np
>>> x=np.array([1,2,3,4.001,5])
>>> y=np.array([1,1.999,3,4.01,5.1])
>>> print(np.allclose(x,y))
False
>>> print(np.allclose(x,y,rtol=0.2)) # 设置相对误差参数
True
>>> print(np.allclose(x,y,atol=0.2)) # 设置绝对误差参数
True
>>> print(np.isclose(x,y))
[ True False  True False False]
>>> print(np.isclose(x,y,atol=0.2))
[ True  True  True  True  True]

Modify the value of an element in an array

>>> import numpy as np
>>> x=np.arange(8)
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.append(x,8) # 返回新数组,在尾部追加一个元素
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> np.append(x,[9,10]) # 返回新数组,在尾部追加多个元素
array([ 0,  1,  2,  3,  4,  5,  6,  7,  9, 10])
>>> np.insert(x,1,8) # 返回新数组,插入元素
array([0, 8, 1, 2, 3, 4, 5, 6, 7])
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> x[3]=8 # 使用下标的形式原地修改元素值
>>> x # 原来的数组被修改了
array([0, 1, 2, 8, 4, 5, 6, 7])
>>> x=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> x
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> x[0,2]=4 # 修改第1行第3列的元素值
>>> x
array([[1, 2, 4],
       [4, 5, 6],
       [7, 8, 9]])
>>> x[1:,1:]=1 # 切片,把行下标大于等于1,列下标也大于等于1的元素值都设置为1
>>> x
array([[1, 2, 4],
       [4, 1, 1],
       [7, 1, 1]])
>>> x[1:,1:]=[1,2] # 同时修改多个元素值
>>> x
array([[1, 2, 4],
       [4, 1, 2],
       [7, 1, 2]])
>>> x[1:,1:]=[[1,2],[3,4]] # 同时修改多个元素值
>>> x
array([[1, 2, 4],
       [4, 1, 2],
       [7, 3, 4]])

Operations on Arrays and Scalars

>>> import numpy as np
>>> x=np.array((1,2,3,4,5)) # 创建数组对象
>>> x
array([1, 2, 3, 4, 5])
>>> x*2 # 数组与数值相乘,返回新数组
array([ 2,  4,  6,  8, 10])
>>> x/2
array([0.5, 1. , 1.5, 2. , 2.5])
>>> x//2
array([0, 1, 1, 2, 2], dtype=int32)
>>> x**3
array([  1,   8,  27,  64, 125], dtype=int32)
>>> x+2
array([3, 4, 5, 6, 7])
>>> x%3
array([1, 2, 0, 1, 2], dtype=int32)
>>> 2**x
array([ 2,  4,  8, 16, 32], dtype=int32)
>>> 2/x
array([2.        , 1.        , 0.66666667, 0.5       , 0.4       ])
>>> 63//x
array([63, 31, 21, 15, 12], dtype=int32)

Operations on Arrays and Arrays

>>> np.array([1,2,3,4])+np.array([4,3,2,1]) # 等长数组相加,对应元素的值相加
array([5, 5, 5, 5])
>>> np.array([1,2,3,4])+np.array([4]) # 数组中每个元素的值加4
array([5, 6, 7, 8])
>>> a=np.array((1,2,3))
>>> a+a # 等长数组之间的加法运算,对应元素的值相加
array([2, 4, 6])
>>> a*a
array([1, 4, 9])
>>> a-a
array([0, 0, 0])
>>> a/a
array([1., 1., 1.])
>>> a**a
array([ 1,  4, 27])
>>> b=np.array(([1,2,3][4,5,6],[7,8,9]))
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    b=np.array(([1,2,3][4,5,6],[7,8,9]))
TypeError: list indices must be integers or slices, not tuple
>>> b=np.array(([1,2,3],[4,5,6],[7,8,9]))
>>> a
array([1, 2, 3])
>>> b
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> c=a*b # 不同维度的数组与数组相乘,广播
>>> c
array([[ 1,  4,  9],
       [ 4, 10, 18],
       [ 7, 16, 27]])
>>> a+b
array([[ 2,  4,  6],
       [ 5,  7,  9],
       [ 8, 10, 12]])

array sort

>>> x=np.array([3,1,2])
>>> np.argsort(x) # 返回升序排序后元素的原下标
array([1, 2, 0], dtype=int64)
>>> x[_] # 使用数组的元素值作为下标,获取原数组中对应位置的元素
array([1, 2, 3])
>>> x=np.array([3,1,2,4])
>>> x.argmax(),x.argmin() # 最大值和最小值的下标
(3, 1)
>>> np.argsort(x)
array([1, 2, 0, 3], dtype=int64)
>>> x[_]
array([1, 2, 3, 4])
>>> x.sort() # 原地排序
>>> x
array([1, 2, 3, 4])
>>> x=np.random.randint(1,10,(2,5))
>>> x
array([[9, 7, 8, 9, 5],
       [8, 3, 9, 9, 4]])
>>> x.sort(axis=1) # 横向排序,注意纵向的元素对应关系变化了
>>> x
array([[5, 7, 8, 9, 9],
       [3, 4, 8, 9, 9]])

Array inner product operation

For the sum of two equal-length arrays x(x1,x2,x3,...,xn), y(y1,y2,y3,...,yn)the inner product is the sum of the products of elements at corresponding positions in the two arrays. Calculated as follows:x1*y1+x2*y2+x3*y3+...+xn*yn

>>> x=np.array((1,2,3))
>>> y=np.array((4,5,6))
>>> print(np.dot(x,y)) # 输出结果都是32
32
>>> x.dot(y)
32
>>> sum(x*y)
32

access the elements in the array

>>> b=np.array(([1,2,3],[4,5,6],[7,8,9]))
>>> b
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> b[0] # 第1行所有元素
array([1, 2, 3])
>>> b[0][0] # 第1行第1列元素
1
>>> b[0,2] # 第1行第3列的元素,相当于b[0][2]
3
>>> b[[0,1]] # 第1行和第2行所有元素,只指定行下标,不指定列下标,表示所有列
array([[1, 2, 3],
       [4, 5, 6]])
>>> b[[0,2,1],[2,1,0]] #第1行第3列、第3行第2列、第2行第1列的元素,第一个列表表示行下标,第二个列表表示列下标
array([3, 8, 4])
>>> a=np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[::-1] # 反向切片
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> a[::2] # 步长为2
array([0, 2, 4, 6, 8])
>>> a[:5] # 前五个元素
array([0, 1, 2, 3, 4])
>>> c=np.arange(25) # 创建数组,1行25列
>>> c.shape=5,5 # 修改数组形状为5行5列
>>> c
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]])
>>> c[0,2:5] # 第1行第3,4,5列元素
array([2, 3, 4])
>>> c[1] # 行下标为1(第2行)的所有元素
array([5, 6, 7, 8, 9])
>>> c[2:5,2:5] # 行下标和列下标都介于[2,5)之间的元素值
array([[12, 13, 14],
       [17, 18, 19],
       [22, 23, 24]])
>>> c[[1,3],[2,4]] # 第2行第3列和第4行第5列的元素
array([ 7, 19])
>>> c[[1,3],2:4] # 第2行和第4行的第3、4列
array([[ 7,  8],
       [17, 18]])
>>> c[:,[2,4]] # 第3列和第5列的所有元素,冒号表示所有行
array([[ 2,  4],
       [ 7,  9],
       [12, 14],
       [17, 19],
       [22, 24]])
>>> c[:,3] # 第4列所有元素
array([ 3,  8, 13, 18, 23])
>>> c[1,3] # 第2行第4列元素
8
>>> c[[1,3]] # 第2行和第4行所有元素
array([[ 5,  6,  7,  8,  9],
       [15, 16, 17, 18, 19]])
>>> c[[1,3]][:,[2,4]] # 第2,4行的3,5列元素
array([[ 7,  9],
       [17, 19]])

Array support for function operations

>>> x=np.arange(0,100,10,dtype=np.float64)
>>> x
array([ 0., 10., 20., 30., 40., 50., 60., 70., 80., 90.])
>>> np.sin(x) # 一维数组中所有元素的值求正弦值
array([ 0.        , -0.54402111,  0.91294525, -0.98803162,  0.74511316,
       -0.26237485, -0.30481062,  0.77389068, -0.99388865,  0.89399666])
>>> x=np.array(([1,2,3],[4,5,6],[7,8,9]))
>>> x
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.cos(x) # 二维数组中所有元素的值求余弦值
array([[ 0.54030231, -0.41614684, -0.9899925 ],
       [-0.65364362,  0.28366219,  0.96017029],
       [ 0.75390225, -0.14550003, -0.91113026]])
>>> np.round(np.cos(x)) # 四舍五入
array([[ 1., -0., -1.],
       [-1.,  0.,  1.],
       [ 1., -0., -1.]])
>>> np.ceil(x/2) # 向上取整
array([[1., 1., 2.],
       [2., 3., 3.],
       [4., 4., 5.]])

change array shape

>>> x=np.arange(1,11,1)
>>> x
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
>>> x.shape # 查看数组的形状
(10,)
>>> x.size # 数组中元素的数量
10
>>> x.shape=2,5 # 改为2行5列
>>> x
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> x.shape
(2, 5)
>>> x.shape=5,-1 # -1表示自动计算
>>> x
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])
>>> x=x.reshape(2,5) # reshape()方法返回新数组
>>> x
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> x=np.array(range(5))
>>> x
array([0, 1, 2, 3, 4])
>>> x.resize((1,10),refcheck=False) # resize()可以修改数组元素个数
>>> x
array([[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]])
>>> np.resize(x,(1,3)) # 使用numpy的resize()返回新数组
array([[0, 1, 2]])
>>> x # 不对原数组进行任何修改
array([[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]])

array boolean operations

>>> x=np.random.rand(10) # 包含10个随机数的数组
>>> x
array([0.0625734 , 0.86626077, 0.56413995, 0.76362196, 0.8732393 ,
       0.68486165, 0.80884492, 0.82828753, 0.32747044, 0.09202415])
>>> x>0.5 # 比较数组中每个元素值是否大于0.5
array([False,  True,  True,  True,  True,  True,  True,  True, False,
       False])
>>> x[x>0.5] # 获取数组中大于0.5的元素
array([0.86626077, 0.56413995, 0.76362196, 0.8732393 , 0.68486165,
       0.80884492, 0.82828753])
>>> sum((x>0.4)&(x<0.6)) # 值大于0.4且小于0.6的元素的数量,在Python内部,True表示1,False表示0
1
>>> np.all(x<1) # 测试是否全部元素都小于1
True
>>> np.any(x>0.8) # 测试是否存在大于0.8的元素
True
>>> a=np.array([1,2,3])
>>> b=np.array([3,2,1])
>>> a>b # 两个数组中对应位置上的元素的值进行比较
array([False, False,  True])
>>> a[a>b] # 数组a中大于数组b中对应位置上元素的值
array([3])
>>> a==b
array([False,  True, False])
>>> a[a==b]
array([2])
>>> x=np.arange(1,10)
>>> x
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> x[(x%2==0)&(x>5)] # 大于5的偶数
array([6, 8])
>>> x[(x%2==0)|(x>5)] # 大于5的元素或偶数
array([2, 4, 6, 7, 8, 9])

piecewise function

>>> x=np.random.randint(0,10,size=(1,10))
>>> x
array([[6, 0, 6, 2, 9, 9, 3, 9, 4, 5]])
>>> np.where(x<5,0,1) # 小于5的元素值对应0,其他对应1
array([[1, 0, 1, 0, 1, 1, 0, 1, 0, 1]])
>>> x.resize((2,5))
>>> x
array([[6, 0, 6, 2, 9],
       [9, 3, 9, 4, 5]])
>>> np.piecewise(x,[x<4,x>7],[-1,lambda x:x*3]) # 小于4的元素变为-1,大于7的元素乘以3,其他元素变为0
array([[ 0, -1,  0, -1, 27],
       [27, -1, 27,  0,  0]])

Array stacking and merging

>>> arr1=np.array([1,2,3])
>>> arr2=np.array([4,5,6])
>>> np.hstack((arr1,arr2)) # 水平堆叠
array([1, 2, 3, 4, 5, 6])
>>> np.vstack((arr1,arr2)) # 垂直堆叠
array([[1, 2, 3],
       [4, 5, 6]])
>>> arr3=np.array([[1],[2],[3]])
>>> arr4=np.array([[4],[5],[6]])
>>> np.hstack((arr3,arr4))
array([[1, 4],
       [2, 5],
       [3, 6]])
>>> np.vstack((arr3,arr4))
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
>>> np.concatenate((arr3,arr4)) # axis默认为0,按行进行合并
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6]])
>>> np.concatenate((arr3,arr4),axis=1)
array([[1, 4],
       [2, 5],
       [3, 6]])

Guess you like

Origin blog.csdn.net/weixin_46322367/article/details/129329100