【问题标题】:With numpy, How can I insert a 2 dimentional array into a 3 dimentional array?使用 numpy,如何将 2 维数组插入 3 维数组?
【发布时间】:2021-03-14 15:12:03
【问题描述】:

我是 python 新手。当我尝试将二维数组插入 3d 数组时,出现如下错误:

ValueError: could not broadcast input array from shape (9,9) into shape (9)

这是我的代码:

        tables = np.zeros((10, 9, 9))
        currentRoundTable = np.zeros((9, 9))
        np.insert(tables, 0, currentRoundTable)
        tables.pop()

目的是创建一个队列,其中tables[0]总是最新的元素(一个二维数组),最旧的会被弹出。

有谁知道我该如何解决这个问题?非常感谢!

【问题讨论】:

  • 只需将axis=0 添加到插入调用中。顺便说一句,你不能从这样的数组中弹出。
  • @FelipeLanza 嗨,谢谢!它起作用了,现在我的问题变成了:我怎样才能从这样的数组中弹出。哈哈!
  • numpy 数组对于类似队列的操作不是最佳的。插入和删除元素的操作都需要创建一个全新的数组,这是一个相对昂贵的操作。
  • 如果您需要一个数组队列,collections.deque 可能会更好。

标签: python arrays python-3.x numpy


【解决方案1】:

np.insert 返回一个新数组,因此您总是需要重新分配它。无论如何,您可以考虑同时处理插入和弹出等效项:

new_table = np.vstack([currentRoundTable[None, :, :], tables[:-1]])
# or to keep your own logic
new_table = np.insert(tables, 0, currentRoundTable, axis=0)[:-1]

也就是说,正如@hpaulj 所建议的,数组对于处理队列确实不是最佳的。这是一个更理想的选择:

from collections import deque

queue = deque(tables, maxlen=10)
queue.pop()  # Drop the last item
queue.insert(0, currentRoundTable)  # Add the new table on top

【讨论】:

  • Good 从帖子 +1 中学到了很多关于 python 索引的知识
猜你喜欢
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多