0

I want to use vectorization to do some computation on numpy.ndarray. Suppose I have the following vectorized function:

import numpy as np
fun = lambda x:x[0]+x[1]
fun = np.vectorize(fun)

and the following numpy.ndarray

 a = range(10)
 b = range(10)
 c = np.array([a,b])

When I apply

 result = fun(c)

I obtain the following error

 IndexError: invalid index to scalar variable.

\Why is this the case and how should I fix it?

2
  • 1
    Don't use np.vectorize if you are looking for performance. Look into ufuncs rather. Commented May 3, 2017 at 19:28
  • What do you expect fun to do? A vectorized function will apply to every element of an array, so how is x[0] + x[1] suppose to work when x is a number? Also, I second the call not to use np.vectorize, it's essentially a thin wrapper around a vanilla Python loop. Commented May 3, 2017 at 19:36

1 Answer 1

1

np.vectorize feeds scalar values to your function. It iterates on the input arrays, broadcasting if needed, and feeds func scalars, not arrays or lists. It then collects the values in a new array of shape and dtype that it deduces.

For example:

In [108]: fun = lambda x,y: x+y
     ...: fun = np.vectorize(fun)

In [110]: a=np.arange(10); b=np.arange(10)
In [111]: fun(a,b)
Out[111]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

It is not 'vectorize' in the sense of turning your function into fast compiled code. It's a convenience, saving you some work in setting up an interation.

I'm sure your fun is just a example, but as written it is already 'vectorized'

In [112]: (lambda x,y: x+y)(a,b) 
Out[112]: array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

Expressing your calculation with numpy primitives, without iteration, is the true 'vectorization'. That isn't always possible, but if you feel you must fall back on np.vectorize remember that

  • it feeds scalars
  • it will iterate at Python speeds
  • use otypes if possible
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.