将numpy int和float数组相乘

问题描述:

我想将 int16 数组乘以 float 数组,并进行自动舍入,但这会失败:

I'd like to multiply an int16 array but a float array, with auto rounding, but this fails :

import numpy

A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)
B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64)

A *= B

我得到:


TypeError :无法将dtype('float64')的ufunc乘法输出转换为dtype('int16'),具有强制转换规则'same_kind'

TypeError: Cannot cast ufunc multiply output from dtype('float64') to dtype('int16') with casting rule 'same_kind'


解决此问题的两种方法:

您可以通过替换解决此问题

You can solve this by replacing

A *= B

A = (A * B)

numpy.multiply(A, B, out=A, casting='unsafe')