【问题标题】:Why is np nan convertible to int by `astype` (but not by `int`)?为什么 np nan 可以通过 `astype` 转换为 int(但不能通过 `int`)?
【发布时间】:2022-07-07 16:05:01
【问题描述】:

这个问题来自一个对我来说非常不直观的发现。如果尝试以下操作:

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

那么第一个输出是[-9223372036854775808],第二个输出ValueError: cannot convert float NaN to integer。我希望以后的行为,我绝对不希望有人可以将np.nan 转换为int。为什么会这样?为什么可以使用astypenp.nan 转换为int?它有什么功能或意义吗?

【问题讨论】:

    标签: python numpy integer nan


    【解决方案1】:

    .astype 具有可选参数casting,其默认值为'unsafe'。允许以下值

    • “no”表示根本不应该转换数据类型。
    • ‘equiv’表示只允许字节顺序更改。
    • “安全”意味着只允许可以保留值的强制转换。
    • “same_kind”表示只允许安全转换或种类内的转换,如 float64 到 float32。
    • “不安全”表示可以进行任何数据转换。

    当一次尝试时

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

    出现以下错误

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

    【讨论】:

    • 您好,感谢您的回答。还缺少一件 - 是否有原因将默认设置为unsafe,即。是否有理由希望将其作为默认行为?因为它违背了显式/隐式,并且错误永远不应该通过python的禅宗,不是吗?
    猜你喜欢
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    相关资源
    最近更新 更多