Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 848
Felix Avatar asked Apr 08 '15 15:04

Felix


People also ask

How do I check if NumPy is numeric?

NumPy isnumeric() function The isnumeric() function of the NumPy library returns True if there are only numeric characters in the string, otherwise, this function will return False.

How do I check if a number is Dtype?

is_numeric_dtype. Check whether the provided array or dtype is of a numeric dtype.

How can you identify the datatype of a given NumPy array?

The data type of an array in Python can be found with the dtype() function. Within this dtype() function, you specify the array. Python will then return the data type of the array.

What does Asarray do in NumPy?

NumPy: asarray() function The asarray() function is used to convert an given input to an array. Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. By default, the data-type is inferred from the input data.


Video Answer


1 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

like image 153
Alex Riley Avatar answered Sep 29 '22 03:09

Alex Riley