Python Numpy,将数组与标量相乘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53485221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Numpy, multiply array with scalar
提问by ktv6
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:
是否可以使用 ufuncs https://docs.scipy.org/doc/numpy/reference/ufuncs.html
为了将函数映射到数组(1D 和/或 2D)和标量
如果不是,我的实现方式是什么这个?
例如:
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.
如果与问题相关,我正在使用 python 2.7。
回答by iz_
You can multiply numpy arrays by scalars and it just works.
您可以将 numpy 数组乘以标量,它就可以工作。
>>> 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.]])
回答by Srce Cde
Using .multiply()(ufunc multiply)
使用.multiply()(ufunc乘法)
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.]])