I have a function which accepts array-like objects (i.e. np.ndarray or possibly nested lists/tuples). I need to check whether a given object can be safely coerced to a given target dtype (e.g. float).
The function np.can_cast(...) with the default casting='safe' is somewhat handy, but
- only acceps np.ndarray (or scalars), not for lists/tuples;
- does not consider the actual data range, only source dtype (e.g.
np.can_cast(np.ndarray([1],dtype='int64'),'int32')isFalseeven though1is perfectly representable in int32.
So two separate questions:
How can I check that array-like sequence is safely convertible to a dtype? (
np.array([1.1,2.2,3.3],dtype='i')will happily truncate the floats)How can I check that a np.ndarray is safely convertible to a target dtype based on actual values in the array?