-
-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Description
Describe the issue:
When vectorizing a function having array-like outputs, if the function is called with scalar (0-d) inputs, the array-like outputs are transformed to (object) arrays. This results in the output types changing with respect to the inputs' dimensionality, which shouldn't be the case.
This issue comes from the fact that np.frompyfunc does not wrap the outputs in arrays if the inputs are scalars (which I find quite nice). Then, when the following lines are applied (in vectorize), the array-like outputs are transformed into arrays instead of being wrapped into scalar arrays like other types (e.g. set).
numpy/numpy/lib/function_base.py
Lines 2389 to 2393 in a8fd84d
| if ufunc.nout == 1: | |
| res = asanyarray(outputs, dtype=otypes[0]) | |
| else: | |
| res = tuple([asanyarray(x, dtype=t) | |
| for x, t in zip(outputs, otypes)]) |
A simple solution would be to not apply asanyarray if the otype is object.
P.S. The list comprehension at line 2392 is superfluous.
Reproduce the code example:
>>> import numpy as np
>>> vf = np.vectorize(lambda _: np.arange(3), otypes=[object])
>>> vf([0])
array([array([0, 1, 2])], dtype=object)
>>> vf(0) # should be array([0, 1, 2]) or array(array([0, 1, 2]), dtype=object)
array([0, 1, 2], dtype=object)Error message:
No response
NumPy/Python version information:
>>> import sys, numpy; print(numpy.__version__, sys.version)
1.21.0 3.9.7 (default, Sep 16 2021, 13:09:58)
[GCC 7.5.0]