本文介绍了Numpy,将数组与标量相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用 ufuncs https://docs.scipy.org/doc/numpy/reference/ufuncs.html
为了将函数映射到数组(一维和/或二维)和标量
如果不是,我的方法是什么?
例如:
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.0, 4.0, 6.0]);a_2 * b = 数组([[2., 4.], [6., 8.]])
如果与问题相关,我将使用 python 2.7.
解决方案
您可以将 numpy 数组乘以标量,它就可以工作.
>>>将 numpy 导入为 np>>>np.array([1, 2, 3]) * 2数组([2, 4, 6])>>>np.array([[1, 2, 3], [4, 5, 6]]) * 2数组([[ 2, 4, 6],[ 8, 10, 12]])这也是一个非常快速高效的操作.以您的示例:
>>>a_1 = np.array([1.0, 2.0, 3.0])>>>a_2 = np.array([[1., 2.], [3., 4.]])>>>b = 2.0>>>a_1 * b数组([2., 4., 6.])>>>a_2 * b数组([[2., 4.],[6., 8.]])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.
解决方案
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.]])
这篇关于Numpy,将数组与标量相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!