【问题标题】:How to replace a section of an array with another array [numpy]如何用另一个数组替换数组的一部分[numpy]
【发布时间】:2016-05-04 05:00:31
【问题描述】:

我正在尝试用另一个数组替换数组的一部分,如下所示:

data[1:-1,1:-1,1] = tmp_data

data[1:-1,1:-1,1]tmp_data 的大小相同。我收到此错误消息:

TypeError: 'tuple' object does not support item assignment

为什么会这样?我该如何解决?谢谢

【问题讨论】:

  • data 似乎是一个元组,而不是一个数组。
  • print(type(data[1:-1,1:-1,1])) yield in <class 'numpy.ndarray'> 然后程序在同一行停止TypeError: tuple indices must be integers or slices, not tuple
  • 那...没有意义。你是说print 打印<class 'numpy.ndarray'>,然后print 产生一个TypeError?这简直是​​不可能的。
  • 我也不明白,但那正在发生。 print(type(data[1:-1,1:-1,1])) TypeError: tuple indices must be integers or slices, not tuple 但它仍然打印 <class 'numpy.ndarray'> 关于如何解决问题的任何想法?
  • 这是循环吗?听起来好像有一个循环,data 在不同的迭代中具有不同的类型,并且您没有正确区分在哪个迭代中会发生什么。

标签: python arrays python-3.x numpy


【解决方案1】:

由于两个数组的大小相同。 data[1:-1,1:-1,1] = tmp_data 不会成功。 您需要提供将固定到分配索引中的 tmp_data 的大小。

>>> import numpy as np
>>> a = np.arange(20).reshape(2,2, 5)
>>> b = np.arange(21,41).reshape(2,2, 5)
>>> a[0:1,0:1,1]=b[0:1,0:1,1]
>>> a
array([[[ 0, 22,  2,  3,  4],
        [ 5,  6,  7,  8,  9]],

       [[10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19]]])

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 2017-04-03
    • 2021-10-13
    • 2021-10-10
    相关资源
    最近更新 更多