0

I have a function that takes 2 numpy arrays as input and returns a number (real function much more complicated than the example below) :

def the_func(x,y): 
    return np.sum(x)*np.sum(y)
>>> the_func([2,3,4],[10,11,12])
297

So far , so good.

But then

>>> the_func([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]])
441

instead of the expected [36,225]

So I tried to vectorize the initial function :

vfunc = np.vectorize(the_func)

But

>>> vfunc([[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]])
array([[ 1,  4,  9],
       [16, 25, 36]])

How can I get that function to return my result in the shape that I'd like to see (in the last example [36,225] = [(1+2+3)*(1+2+3),(4+5+6)*(4+5+6)]) ?

Chapo
  • 2,563
  • 3
  • 30
  • 60
  • `vectorize` passes scalar values from the input arrays to your function. Your inputs are both (2,3) (when converted to arrays), so the output is also (2,3). In effect `the_func(1,1)`, `the_func(2,2)` etc. Also, `vectorize` does NOT speed up your code (compared to a direct iteration). – hpaulj Oct 25 '19 at 07:02
  • Yes was not trying to speed up in that case just writing multiple for loops elegantly – Chapo Oct 25 '19 at 07:03
  • Aren't you just doing one loop? `[vfunc(x,y) for x, y in zip(a, b)]` – hpaulj Oct 25 '19 at 07:12
  • Yes I could have zipped everything you're right. My actual code is a bit more complicated and I ended up modifying the function to take the shape into account instead of calling the function multiple times. – Chapo Oct 25 '19 at 07:15
  • Loop within instead of outside basically – Chapo Oct 25 '19 at 07:15
  • I'm still stuck on that one though : https://stackoverflow.com/questions/58552951/convert-float-to-string-numba-python-numpy-array. I know it's not that interesting but I don't understand what I'm doing wrong. – Chapo Oct 25 '19 at 07:36

1 Answers1

1

You should use the axis keyword argument for this to specify along with dimension it should sum. In your example, change your function to this:

def the_func(x,y): 
    return np.sum(x, axis=1)*np.sum(y, axis=1)

Running it on your sample input gave the result [36 255].

ashiswin
  • 637
  • 5
  • 11