Numpy 中数组上的算术运算符使用元素级别。最后的结果使用新的一个数组来返回。
import numpy as np a = np.array( [20,30,40,50] ) b = np.arange(4) b Out[113]: array([0, 1, 2, 3]) c = a -b c Out[114]: array([20, 29, 38, 47]) b ** 2 Out[115]: array([0, 1, 4, 9], dtype=int32) a < 34 Out[116]: array([ True, True, False, False])
需要注意的是,乘法运算符*
的运算在NumPy数组中也是元素级别的(这与许多矩阵语言不同)。如果想要执行矩阵乘积,可以使用dot
函数:
A = np.array( [[1,1], [0,1]] ) B = np.array( [[2,0], [3,4]] ) A Out[117]: array([[1, 1], [0, 1]]) B Out[118]: array([[2, 0], [3, 4]]) A * B Out[119]: array([[2, 0], [0, 4]]) A.dot(B) Out[120]: array([[5, 4], [3, 4]]) np.dot(A,B) Out[121]: array([[5, 4], [3, 4]])
某些操作(如+=
和*=
)可以修改现有数组,而不是创建新数组。
a = np.ones((2,3), dtype=np.int32) a *= 3 a Out[122]: array([[3, 3, 3], [3, 3, 3]]) b = np.random.random((2,3)) b Out[124]: array([[0.39895014, 0.30638211, 0.9011525 ], [0.6135912 , 0.02488626, 0.67726569]]) a.dtype Out[125]: dtype(‘int32‘) b.dtype Out[126]: dtype(‘float64‘) b += a b Out[128]: array([[3.39895014, 3.30638211, 3.9011525 ], [3.6135912 , 3.02488626, 3.67726569]]) a += b Traceback (most recent call last): File "D:\pytho3.6\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-129-294cacd62d6f>", line 1, in <module> a += b TypeError: Cannot cast ufunc add output from dtype(‘float64‘) to dtype(‘int32‘) with casting rule ‘same_kind‘
当使用不同类型的数组操作时,结果数组的类型对应于更一般或更精确的数组(称为向上转换的行为)。
由于定义 a时,数据类型指定为np.int32,而 a+b 生成的数据类型为 np.float64,所以自动转换出错。
原文:https://www.cnblogs.com/zhangyafei/p/10567014.html