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?
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.
is_numeric_dtype. Check whether the provided array or dtype is of a numeric dtype.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With