[英]Why is np nan convertible to int by `astype` (but not by `int`)?
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
.那么第一个的输出是
[-9223372036854775808]
,第二个引发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.我期待后来的行为,我绝对不希望有人可以将
np.nan
转换为 int。 Why is this like that?为什么会这样? Why can one use
astype
to convert np.nan
to int?为什么可以使用
astype
将np.nan
转换为 int? Does it have any functionality or meaning?它有什么功能或意义吗?
.astype
has optional argument casting
whose default value is 'unsafe'
. .astype
具有可选参数casting
,其默认值为'unsafe'
。 Following values are allowed允许以下值
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.