将乘法结果保存到现有数组
Save result of multiplication to existing array
考虑以下代码:
a = numpy.array([1,2,3,4])
b = numpy.array([5,6,7,8])
# here a new array (b*2) will be created and name 'a' will be assigned to it
a = b * 2
那么,numpy 是否可以直接将 b*2
的结果写入已分配给 a
的内存中,而无需分配新数组?
是的,这是可能的 - 您需要使用 np.multiply
with its out
参数:
np.multiply(b, 2, out=a)
数组 a
现在填充了 b * 2
的结果(并且没有分配新内存来保存函数的输出)。
NumPy 的所有 ufunc 都有 out
参数,这在处理大型数组时特别方便;它通过允许重复使用数组来帮助将内存消耗保持在最低限度。唯一需要注意的是数组必须正确 size/shape 来保存函数的输出。
考虑以下代码:
a = numpy.array([1,2,3,4])
b = numpy.array([5,6,7,8])
# here a new array (b*2) will be created and name 'a' will be assigned to it
a = b * 2
那么,numpy 是否可以直接将 b*2
的结果写入已分配给 a
的内存中,而无需分配新数组?
是的,这是可能的 - 您需要使用 np.multiply
with its out
参数:
np.multiply(b, 2, out=a)
数组 a
现在填充了 b * 2
的结果(并且没有分配新内存来保存函数的输出)。
NumPy 的所有 ufunc 都有 out
参数,这在处理大型数组时特别方便;它通过允许重复使用数组来帮助将内存消耗保持在最低限度。唯一需要注意的是数组必须正确 size/shape 来保存函数的输出。