28

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.

ktv6
  • 463
  • 1
  • 5
  • 12

2 Answers2

45

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.]])
iz_
  • 13,337
  • 2
  • 19
  • 37
  • does this work for any of ufuncs? – ktv6 Nov 26 '18 at 16:33
  • I'm not sure what you mean, but [this link](https://docs.scipy.org/doc/numpy-1.15.1/reference/ufuncs.html#ufuncs-broadcasting) may help. – iz_ Nov 26 '18 at 16:35
8

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.]])
Srce Cde
  • 1,534
  • 8
  • 14