0

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.

thor
  • 21,418
  • 31
  • 87
  • 173
  • That linked answer does not demonstrate what you think. It applies `x**2` to the whole array, which in turn uses standard `numpy` to perform elementwise `**`. That's not a scalar type function. – hpaulj Jul 29 '18 at 16:32
  • For your case `res_exp` is as good as it gets. `vectorize` and `frompyfunc` can make broadcasting convenient, but not faster. But with a scalar 'foo', and 1d `arr`, you don't need broadcasting. – hpaulj Jul 29 '18 at 16:34
  • Read the other answers in your link – hpaulj Jul 29 '18 at 17:50
  • @hpaulj Thanks. I thought that's a bit too magical. Just to clarify, numpy didn't apply the scalar function on the array. Instead, it applied an element-wise array function in that example?? – thor Jul 29 '18 at 18:04
  • 2
    yes, the operator was translated into a call to an array method. – hpaulj Jul 29 '18 at 18:06

0 Answers0