【问题标题】:Why astype(uint) on np.array doesn't change type of an element of the np.array?为什么 np.array 上的 astype(uint) 不会改变 np.array 元素的类型?
【发布时间】:2014-01-21 07:11:30
【问题描述】:

当使用 astype 将 np.array 转换为 uint8 时,数组元素的类型不会改变。

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x.astype(uint8)
array([[1, 2],
       [1, 2]], dtype=uint8)
 >>> type(x[0,0])
<type 'numpy.float64'>

为什么元素仍然是 float64 而不是 uint8

【问题讨论】:

  • 作为一般规则:如果一个方法返回一些东西,那么它不会修改原始对象。如果它没有返回任何东西,那么它确实会修改原始对象。这几乎总是适用于内置对象、标准库和大多数其他库。在您的示例中,很明显 astype 正在返回一些东西。

标签: python python-2.7 numpy


【解决方案1】:

astype 返回原始数组的副本。

改用x = x.astype(uint8)

【讨论】:

    【解决方案2】:

    astype 返回一个数组的副本,所以你必须分配它:

    x = x.astype(uint8)
    

    【讨论】:

      猜你喜欢
      • 2021-04-07
      • 1970-01-01
      • 2017-09-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多