Suppose I have this:
def incrementElements(x):
return x+1
but I want to modify it so that it can take either a numpy array, an iterable, or a scalar, and promote the argument to a numpy array and add 1 to each element.
How could I do that? I suppose I could test argument class but that seems like a bad idea. If I do this:
def incrementElements(x):
return numpy.array(x)+1
it works properly on arrays or iterables but not scalars. The problem here is that numpy.array(x) for scalar x produces some weird object that is contained by a numpy array but isn’t a “real” array; if I add a scalar to it, the result is demoted to a scalar.
You could try
np.asarray(x)is the equivalent ofnp.array(x, copy=False), meaning that a scalar or an iterable will be transformed to andarray, but ifxis already andarray, its data will not be copied.If you pass a scalar and want a
ndarrayas output (not a scalar), you can use:The
ndmin=1argument will force the array to have at least one dimension. Usendmin=2for at least 2 dimensions, and so forth. You can also use its equivalentnp.atleast_1d(ornp.atleast_2dfor the 2D version…)