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.
Numpy multiply array by scalar In order to multiply array by scalar in python, you can use np. multiply() method.
Format of the input arrays One way to use np. multiply, is to have the two input arrays be the exact same shape (i.e., they have the same number of rows and columns). If the input arrays have the same shape, then the Numpy multiply function will multiply the values of the inputs pairwise.
We will be deliberating the simplest and convenient way to multiply a list by a scalar in Python language. First, we create a list and add values to it. Our next step multiplies every item in the list by 3. Then we define a print function that prints the resultant values.
Multiplying a constant to a NumPy array is as easy as multiplying two numbers. To multiply a constant to each and every element of an array, use multiplication arithmetic operator * . To multiplication operator, pass array and constant as operands as shown below. where a is input array and c is a constant.
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.]])
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.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With