41

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?

0

1 Answer 1

82

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.