【问题标题】:Replace a value of a numpy array with infinty用无穷大替换 numpy 数组的值
【发布时间】:2019-10-18 11:01:25
【问题描述】:

假设我有以下 numpy 数组:

import numpy as np
from numpy import inf

x = np.array([1,2,3,4])

我想用无穷大替换该数组的第 j 个索引,例如

x[2] = inf

有什么方法可以实现吗?因为当我尝试时,我收到以下错误:

OverflowError: cannot convert float infinity to integer

感谢您的回答!

【问题讨论】:

    标签: python numpy infinity


    【解决方案1】:

    使用构造函数中的 dtype 参数或使用arr.astype(np.float32) 将数组转换为浮点数,然后再分配 inf,如下所示

    import numpy as np
    from numpy import inf
    
    x = np.array([1,2,3,4], dtype=np.float32)
    x[2] = inf
    

    【讨论】:

      【解决方案2】:

      在声明数组时,像这样声明它:np.array([1, 2, 3], dtype='f')inf in numpyfloat 类型。

      【讨论】:

        【解决方案3】:

        问题是您使用的是“int”数组。

        通过将数组定义为

         x = np.array([1.0,2.0,3.0,4.0])
        

        或者:

         x = np.array([1,2,3,4], dtype='f')
        

        正确执行不会有任何问题。

        在内部,'inf' 是一个 float const,它不支持 int 类型。

        np.iinfo(np.int32).max  # ---- 2147483647
        
        np.iinfo(np.int32).min  # ---- -2147483648
        
        np.iinfo(np.int64).max  # ---- 9223372036854775807
        
        np.iinfo(np.int64).min  # ---- -9223372036854775808
        

        【讨论】:

          【解决方案4】:

          1. 您可以将数组转换为浮点类型。

          x = np.array([0,1,2], dtype=np.float32)
          

          然后你可以使用 np.inf 来计算无穷大数

          2.也可以设置为无穷大的整数个数。

          ii16 = np.iinfo(np.int16)
          x[2] = ii16.max
          

          在第二种方法中,您必须指定您在代码中使用的 ineger。

          【讨论】:

            猜你喜欢
            • 2016-08-13
            • 1970-01-01
            • 2017-09-23
            • 1970-01-01
            • 2022-08-12
            • 1970-01-01
            • 2018-07-12
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多