Numpy, multiply array with scalar [duplicate]

只谈情不闲聊 提交于 2020-06-11 18:49:03

问题


Is it possible to use ufuncs https://docs.scipy.org/doc/numpy/reference/ufuncs.html
In order to map function to array (1D and / or 2D) and scalar
If not what would be my way to achieve this?
For example:

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0  

Expected result:

a_1 * b = array([2.0, 4.0, 6.0]);  
a_2 * b = array([[2., 4.], [6., 8.]])

I`m using python 2.7 if it is relevant to an issue.


回答1:


You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])



回答2:


Using .multiply() (ufunc multiply)

a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0 

np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])


来源:https://stackoverflow.com/questions/53485221/numpy-multiply-array-with-scalar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!