I have a 1d array of values
i = np.arange(0,7,1)
and a function
# Returns a column matrix
def fn(i):
return np.matrix([[i*2,i*3]]).T
fnv = np.vectorize(fn)
then writing
fnv(i)
gives me an error
File "<stdin>", line 1, in <module>
File "c:\Python33\lib\site-packages\numpy\lib\function_base.py",
line 1872, in __call__
return self._vectorize_call(func=func, args=vargs)
File "c:\Python33\lib\site-packages\numpy\lib\function_base.py",
line 1942, in _vectorize_call
copy=False, subok=True, dtype=otypes[0])
ValueError: setting an array element with a sequence.
The result I am looking for is a matrix with two rows and as many columns as in the input array. What is the best notation in numpy to achieve this?
For example i would equal
[1,2,3,4,5,6]
and the output would equal
[[2,4,6,8,10,12],
[3,6,9,12,15,18]]
EDIT
You should try to avoid using
vectorize, because it gives the illusion of numpy efficiency, but inside it’s all python loops.If you really have to deal with user supplied functions that take
ints and return amatrixof shape(2, 1)then there probably isn’t much you can do. But that seems like a really weird use case. If you can replace that with a list of functions that take anintand return anint, and that useufuncswhen needed, i.e.np.sininstead ofmath.sin, you can do the followingJust for your reference, I have timed this vectorization against your proposed one:
So there is an order of magnitude in speed even for small arrays, that grows to a x1000 speed up, available almost for free, for larger arrays.
ORIGINAL ANSWER
Don’t use
vectorizeunless there is no way around it, it’s slow. See the following examplesWhatever your function is, if it can be constructed with numpy’s ufuncs, you can do something like
np.vstack((a, f(a)))and get what you want