This seems like it should be super simple, but the answer is eluding me. I Have done a bunch of google-searches for the answer but don’t feel like any of the results really answered my question, perhaps I’m just searching for the wrong thing? please help:
I am writing a function:
def cheese(array_like, *args, **kwargs): if dtype_of_(array_like) is float: return "macaroni"
dtype_of_(array_like) is float is obviously not functioning code, just something I wrote to give you an idea of what I am trying to accomplish.
What I need is to check whether the input is an iterable of floats (any type of float) or a float. Ie. the input “array_like” can be any iterable which can be converted to a numpy array or can even be a 0-dimensional array or a scalar.
I found this seemingly very similar question here, but I don’t feel that it answered my question.
I also found this other similar question here, but this just concerns scalars, not arrays..
What I have done so far is to do:
def cheese(array_like, *args, **kwargs): np.array(array_like, copy=False).dtype == np.floating: return "macaroni"
But although this works it also gives me a deprecation warning:
np.floatingto a dtype is deprecated. The current result is
float64which is not strictly correct. if np.array(array_like, copy=False).dtype == np.floating:
I think you want
In : np.issubdtype(np.array([1.23,3]).dtype, np.float64) Out: True In : np.issubdtype(np.array([1.23,3]).dtype, np.floating) Out: True In : np.issubdtype(np.array([1.23,3]).dtype, np.inexact) Out: True In : np.issubdtype(np.array([1,3]).dtype, np.floating) Out: False In : np.issubdtype(np.array(34.3).dtype, np.floating) Out: True
I haven’t used this before, but remembered that
release notes had some entries on testing for
I haven’t worked out all the details, but I think a major problem is that you are trying to test different kinds of things.
In : type(np.array(1.23).dtype) Out: numpy.dtype[float64] In : type(np.floating) Out: type
dtype of an array is a
dtype object. But
np.floating is actually a function, though only
np.float64(12.23) can be used as such.
In : np.float64.__mro__ Out: (numpy.float64, numpy.floating, numpy.inexact, numpy.number, numpy.generic, float, object)
np.float64 can be used to both create numpy objects and arrays with a specific dtype, and to test. But
== testing actually involves a bit of behind-the-scenes equivalence, that isn’t obvious to python-level users.