numpy: check safe convertibility of array-like objects, includings nested lists

Viewed 9

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') is False even though 1 is 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?

0 Answers
Related