Felix
Felix

Reputation: 3581

numpy.asarray: how to check up that its result dtype is numeric?

I have to create a numpy.ndarray from array-like data with int, float or complex numbers.

I hope to do it with numpy.asarray function.

I don't want to give it a strict dtype argument, because I want to convert complex values to complex64 or complex128, floats to float32 or float64, etc.

But if I just simply run numpy.ndarray(some_unknown_data) and look at the dtype of its result, how can I understand, that the data is numeric, not object or string or something else?

Upvotes: 40

Views: 18891

Answers (1)

Alex Riley
Alex Riley

Reputation: 176810

You could check if the dtype of the array is a sub-dtype of np.number. For example:

>>> np.issubdtype(np.complex128, np.number)
True
>>> np.issubdtype(np.int32, np.number)
True
>>> np.issubdtype(np.str_, np.number)
False
>>> np.issubdtype('O', np.number) # 'O' is object
False

Essentially, this just checks whether the dtype is below 'number' in the NumPy dtype hierarchy:

enter image description here

Upvotes: 81

Related Questions