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

Question:

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?

Asked By: Felix

||

Answers:

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

Answered By: Alex Riley
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.