Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy, multiply array with scalar [duplicate]

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.

like image 697
ktv6 Avatar asked Nov 26 '18 16:11

ktv6


People also ask

Can you multiply a NumPy array by a scalar?

Numpy multiply array by scalar In order to multiply array by scalar in python, you can use np. multiply() method.

How do you multiply elements in an array NumPy?

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.

How do you multiply a list by a scalar in Python?

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.

How do you multiply an array by a constant in Python NumPy?

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.


2 Answers

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.]]) 
like image 21
Srce Cde Avatar answered Sep 22 '22 02:09

Srce Cde


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.]]) 
like image 96
iz_ Avatar answered Sep 24 '22 02:09

iz_