(note: the original question was a bit different, to which the other answer applies; see the revision history for the original question.)
Is there a uniform way to index numpy arrays, when these arrays could be scalar as well?
I'm trying to write a function that deals with a float, a list of floats, or a 0/1D numpy array. To deal with that uniformly, I use numpy.asarray(), which works fine overall (I don't mind returning a numpy.float64 when the input is a standard Python float).
Problems arise when I need to deal with conditional operations and an intermediate array function, something like:
value = np.asarray(5.5)
mask = value > 5
tmpvalue = np.asarray(np.cos(value))
tmpvalue[mask] = value
This will throw an exception:
Traceback (most recent call last):
File "testscalars.py", line 27, in <module>
tmpvalue[mask] = value
IndexError: 0-d arrays can't be indexed
Is there any elegant solution to this?
np.cosis aufunc. It is wrapped in a layer of C code that ensures correct handling of dimensions, in and out.vectorizeis supposed to do something similar to user functions.