numpy学习——数组的基本运算操作

数组的基本运算操作

numpy支持数组之间的±*/运算,也支持数与数组之间的运算。运算时不会创建一个新的数组,而是在原有数组基础上进行修改。

举一个经常报错的例子:

a = np.ones((3,3), dtype=int)
b = np.ones((3,3), dtype='float64')

a += b
---------------------------------------------------------------------------
UFuncTypeError                            Traceback (most recent call last)
<ipython-input-14-c8d154c33912> in <module>
      2 b = np.ones((3,3), dtype='float64')
      3 
----> 4 a += b

UFuncTypeError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int32') with casting rule 'same_kind'

如果转换一下

>>> a = np.ones((3,3), dtype=int)
>>> b = np.ones((3,3), dtype='float64')

>>> b += a
>>> b

array([[2., 2., 2.],
       [2., 2., 2.],
       [2., 2., 2.]])

原因是因为:a、b数组相加,numpy会首先把a数组元素转换与b数组元素相同的数据类型。a数组类型是整型数,numpy不会把精度高的数转化为精度低的数,所以会引发异常。b数组本身就是浮点数,所以可以把结果赋给b数组。

猜你喜欢

转载自blog.csdn.net/m0_50470999/article/details/108445135
今日推荐