Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np.vectorize giving me IndexError: invalid index to scalar variable

Tags:

python

numpy

trying out something simple and it's frustratingly not working:

def myfunc(a,b):
  return a+b[0]

v = np.vectorize(myfunc, exclude=['b'])

a = np.array([1,2,3])
b = [0]

v(a,b)

This gives me "IndexError: invalid index to scalar variable." Upon printing b, it appears that the b taken in by the function is always 0, instead of [0]. Can I specify which arguments should be vectorized and which should remain constant?

like image 235
djbhindi Avatar asked Jan 08 '23 02:01

djbhindi


2 Answers

When you use excluded=['b'] the keyword parameter b is excluded. Therefore, you must call v with keyword arguments, e.g. v(a=a, b=b) instead of v(a, b).

If you wish to call v with positional arguments with the second positional argument excluded, then use

v = np.vectorize(myfunc)
v.excluded.add(1)

For example,

import numpy as np

def myfunc(a, b):
    return a+b[0]

a = np.array([1,2,3])
b = [0, 1]

v = np.vectorize(myfunc, excluded=['b'])
print(v(a=a, b=b))
# [1 2 3]

v = np.vectorize(myfunc)
v.excluded.add(1)
print(v(a, b))
# [1 2 3]
like image 174
unutbu Avatar answered Jan 14 '23 01:01

unutbu


Well here is the answer:

v.excluded.add(1) works, though passing exclude=['b'] does not, for some reason.

like image 34
djbhindi Avatar answered Jan 14 '23 02:01

djbhindi