Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Raise errors on float->int conversions with NaN, inf  #14412

Copy link
Copy link
Open
@rth

Description

@rth
Issue body actions

With ndarray.astype(..., casting="unsafe") float arrays with NaN/inf will be converted to np.iinfo(dtype).min/max,

>>> np.array([1, np.nan], dtype=np.float32).astype(np.int32)
array([          1, -2147483648], dtype=int32)
>>> np.array([1, np.inf], dtype=np.float32).astype(np.int32)
array([          1, -2147483648], dtype=int32)

(there are also some inconsistencies there cf #6109). This is very bad in practical applications as output data will be wrong by orders of magnitude. Other casting options simply disallow casting float to int.

At the same time, casting from dtype=np.object works as expected,

>>> np.array([1, np.inf], dtype=np.object).astype(np.int32)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: cannot convert float infinity to integer

It could be useful to have some additional casting option allowing to convert int to float, but would error on NaN or inf. This could be done manually,

if array.dtype.kind == 'f' and np.dtype(dtype).kind == 'i':
   # check for overflows and NaN
   _assert_all_finite(array)
result = array.astype(dtype)

but having it in numpy would be useful.

I also wonder if there is really a case when not raising on such conversions is meaningful (even with casting='unsafe'). For instance pandas does this conversions as expected (using numpy dtypes),

>>> pd.Series([1, np.nan], dtype=np.float64).astype(np.int)
[...]
ValueError: Cannot convert non-finite values (NA or inf) to integer

Numpy/Python version information:

>>> import sys, numpy; print(numpy.__version__, sys.version)
1.16.4 3.7.3 (default, Mar 27 2019, 22:11:17) [GCC 7.3.0]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.