【问题标题】:Convert ndarray from float64 to integer将ndarray从float64转换为整数
【发布时间】:2012-02-09 22:50:35
【问题描述】:

我在 python 中有一个 ndarraydtypefloat64。我想将数组转换为整数数组。我该怎么做?

int() 不起作用,因为它表示无法将其转换为标量。更改 dtype 字段本身显然不起作用,因为实际字节没有改变。我似乎在 Google 或文档中找不到任何内容 - 最好的方法是什么?

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    使用.astype

    >>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
    >>> a
    array([ 1.,  2.,  3.,  4.])
    >>> a.astype(numpy.int64)
    array([1, 2, 3, 4])
    

    请参阅documentation 了解更多选项。

    【讨论】:

      【解决方案2】:

      虽然astype 可能是“最佳”选项,但还有其他几种方法可以将其转换为整数数组。我在以下示例中使用了这个arr

      >>> import numpy as np
      >>> arr = np.array([1,2,3,4], dtype=float)
      >>> arr
      array([ 1.,  2.,  3.,  4.])
      

      来自 NumPy 的 int* 函数

      >>> np.int64(arr)
      array([1, 2, 3, 4])
      
      >>> np.int_(arr)
      array([1, 2, 3, 4])
      

      NumPy *array 自己运行:

      >>> np.array(arr, dtype=int)
      array([1, 2, 3, 4])
      
      >>> np.asarray(arr, dtype=int)
      array([1, 2, 3, 4])
      
      >>> np.asanyarray(arr, dtype=int)
      array([1, 2, 3, 4])
      

      astype 方法(已经提到但为了完整起见):

      >>> arr.astype(int)
      array([1, 2, 3, 4])
      

      请注意,将 int 作为 dtype 传递给 astypearray 将默认为取决于您的平台的默认整数类型。例如,在 Windows 上它将是 int32,在 64 位 Linux 和 64 位 Python 上它是 int64。如果您需要特定的整数类型并希望避免平台“歧义”,您应该使用相应的 NumPy 类型,例如 np.int32np.int64

      【讨论】:

        【解决方案3】:

        还有一个关于就地转换数组的非常有用的讨论,In-place type conversion of a NumPy array。如果您担心复制您的数组(这是astype() 所做的),请务必查看链接。

        【讨论】:

          【解决方案4】:

          我只用了

          numpyfloat = (1.0, 2.0, 4.0)
          a = numpy.array(numpyfloat, dtype=numpy.int)
          

          就是这样

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-12-12
            • 2017-09-27
            • 1970-01-01
            • 1970-01-01
            • 2019-05-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多