Home > Software engineering >  Why is np nan convertible to int by `astype` (but not by `int`)?
Why is np nan convertible to int by `astype` (but not by `int`)?

Time:07-09

This question comes from a finding that is very much not intuitive to me. If one tries the following:

import numpy as np
print(np.array([np.nan]).astype(int))
print(int(np.array([np.nan])))

then the output of the first is [-9223372036854775808], and the second raises ValueError: cannot convert float NaN to integer. I'd expect the later behaviour, and I'd definitely not expect that one can convert np.nan to an int. Why is this like that? Why can one use astype to convert np.nan to int? Does it have any functionality or meaning?

CodePudding user response:

.astype has optional argument casting whose default value is 'unsafe'. Following values are allowed

  • ‘no’ means the data types should not be cast at all.
  • ‘equiv’ means only byte-order changes are allowed.
  • ‘safe’ means only casts which can preserve values are allowed.
  • ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
  • ‘unsafe’ means any data conversions may be done.

When one attempt to do

import numpy as np
print(np.array([np.nan]).astype(int, casting="safe"))

one gets following error

TypeError: Cannot cast array from dtype('float64') to dtype('int32') according to the rule 'safe'
  • Related