是将数组的每一元素均与那个单一数据进行计算,并返回同样大小的数组。
备注:参与运算的一个是数组一个是单一的数值。
piece = np.arange(1,5,1)
price = 2
piece
price
piece *price
>>>
array([1, 2, 3, 4])
2
array([2, 4, 6, 8])
1)同方向相同大小一维数组之间运算
行列数相同数组的运算规律:是对应元素间一一进行运算,并返回同样大小的数组。
备注:参与运算的两个数组大小相等。
piece = np.arange(1,5,1)
price = np.arange(6,10,1)
piece
price
piece *price
>>>
array([1, 2, 3, 4])
array([6, 7, 8, 9])
array([ 6, 14, 24, 36])
2)同方向不同大小一维数组之间运算
piece = np.arange(1,5,1)
price = np.arange(6,8,1)
piece
price
piece *price
>>>
array([1, 2, 3, 4])
array([6, 7])
Traceback (most recent call last):
File "" , line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (2,)
3)不同方向——单行数组与单列数组间运算
行数与单列数组的行数相同、列数与单行数组的列数相同。计算结果中第R行第C列的元素是单列数组的第R个元素和单行数组的第C个元素相运算的结果。
备注:参与运算的两个数组一个是单行数组一个是单列数组
piece = np.random.randint(1,5,(3,1))
price = np.random.randint(1,5,(1,3))
piece
price
piece *price
>>>
array([[1],
[3],
[4]])
array([[3, 3, 1]])
array([[ 3, 3, 1],
[ 9, 9, 3],
[12, 12, 4]])
4)不同方向——单行数组与多行数组间运算
piece = np.random.randint(1,4,(1,3))
price = np.random.randint(1,7,(2,3))
piece
price
piece *price
>>>
array([[3, 3, 2]])
array([[5, 4, 1],
[1, 1, 2]])
array([[15, 12, 2],
[ 3, 3, 4]])
5)不同方向——单列数组和多列数组间运算
piece = np.random.randint(1,5,(3,2))
price = np.random.randint(1,5,(3,1))
piece
price
piece *price
>>>
array([[1, 1],
[1, 4],
[4, 4]])
array([[2],
[3],
[2]])
array([[ 2, 2],
[ 3, 12],
[ 8, 8]])
np.newaxis 的功能是增加新的维度,但是要注意 np.newaxis 放的位置不同,产生的矩阵形状也不同。
通常按照如下规则:
np.newaxis 放在哪个位置,就会给哪个位置增加维度
x[:, np.newaxis] ,放在后面,会给列上增加维度
x[np.newaxis, :] ,放在前面,会给行上增加维度
test = np.random.randint(5,15,(2,2))
test.shape
test_add = test[:,np.newaxis]
test_add.shape
>>>
# test
array([[11, 7],
[14, 8]])
(2,2)
# test_add
array([[[11],
[ 7]],
[[14],
[ 8]]])
(2, 2, 1)
values:数组
axis:表示在该位置添加数据(可以是数组)
test = np.random.randint(5,15,(2,2))
test
test.shape
test_add = np.expand_dims(test,axis = 2)
test_add
test_add.shape
>>>
# test
array([[14, 8],
[ 9, 8]])
(2, 2)
# test_add
array([[[14],
[ 8]],
[[ 9],
[ 8]]])
(2, 2, 1)
values:数组
axis:表示在该位置添加数据(可以是数组)
test = np.random.randint(5,15,(1,2,1,2))
test
test.shape
test_add = np.squeeze(test,(0,2))
test_add
test_add.shape
>>>
# test
array([[[[10, 12]],
[[ 6, 9]]]])
(1, 2, 1, 2)
# test_add
array([[10, 12],
[ 6, 9]])
(2, 2)