When trying to map a function
def make_pair(a,b):
return (a,b)
to a numpy array,
arr = np.array([1,2,3])
I intend to do
np.array([make_pair('foo',x) for x in arr])
, but I read that
in newer version of numpy you can simply call the function by passing the numpy array to the function that you wrote for scalar type
I tried to apply the function make_pair
directly to the array (res = make_pair('foo',arr)
), but couldn't get the expected result (mapping it over the array). In the code below:
import numpy as np
def make_pair(a,b):
return (a,b)
arr = np.array([1,2,3])
res_0 = np.array([('foo',1), ('foo',2), ('foo',3)])
res_exp = np.array([make_pair('foo',x) for x in arr])
res = make_pair('foo',arr)
I got:
>>> res
('foo', array([1, 2, 3]))
The function is applied to the array arr
instead of mapped into it (due to the ambiguity).
Is there a way to tell numpy to map the function instead of apply the function on the array? (other than doing the mapping externally with list comprehension as shown)
This is with Python 3.6.5, and latest numpy as of July 2018, Ubuntu 18.04.