广播(broadcast)
广播(broadcast)是numpy对 不同形状(shape)的数组进行数值计算的方式,对数组的算术运算通常在相应的元素上进行。
当运算中的2个数组的形状不同时,numpy将自动触发广播机制:
import numpy as npa = np.array([[0,0,0],[10,10,10],[20,20,20],[30,30,30]])b = np.array([1,2,3])a+b
array([[ 1, 2, 3],[11, 12, 13],[21, 22, 23],[31, 32, 33]])
#广播的规则:# 让所有输入数组都向其中形状最长的数组看齐,形状中不足的部分都通过在前面加1补齐。#输出数组的形状是输入数组形状的各个维度上的最大值#如果输入数组的某个维度和输出数组的对应维度的长度相同或者其长度为1时,这个数组能够用来计算,否则出错#当输入数组的某个维度的长度为1时,沿着此维度运算时都用此维度的第一组值
ndarray的运算
#1、数组与数的运算#numpyd的广播机制再运算过程中,加减乘除的值被广播到所有的元素上t1 = np.arange(24).reshape(6,4)t1+2t1*2t1/2t1-2
array([[-2, -1, 0, 1],[ 2, 3, 4, 5],[ 6, 7, 8, 9],[10, 11, 12, 13],[14, 15, 16, 17],[18, 19, 20, 21]])
#2、数组与数组的运算#同种形状的数组(对应位置进行计算操作)#如果两个数组a和b数组对应位相乘,这要求维数(ndim)相同,且各维度的长度(shape)相同t1 = np.arange(24).reshape((6,4))t2 = np.arange(100,124).reshape((6,4))t1*t2t1+t2t1-t2t1/t2
array([[0. , 0.00990099, 0.01960784, 0.02912621],[0.03846154, 0.04761905, 0.05660377, 0.06542056],[0.07407407, 0.08256881, 0.09090909, 0.0990991 ],[0.10714286, 0.11504425, 0.12280702, 0.13043478],[0.13793103, 0.14529915, 0.15254237, 0.15966387],[0.16666667, 0.17355372, 0.18032787, 0.18699187]])
# # b不同形状的多维数组计算# #行数不同,列数相同,不能进行算术运算# t1 = np.arange(24).reshape((4,6))# t2 = np.arange(18).reshape((3,6))# t1# t2# t1-t2# #报错#行数相同,列数不同,可以进行运算t1 = np.arange(24).reshape((4,6))t2 = np.arange(4).reshape((4,1))print(t1)print(t2)print(t1 - t2)
[[ 0 1 2 3 4 5][ 6 7 8 9 10 11][12 13 14 15 16 17][18 19 20 21 22 23]][[0][1][2][3]][[ 0 1 2 3 4 5][ 5 6 7 8 9 10][10 11 12 13 14 15][15 16 17 18 19 20]]
