【问题标题】:Inserting a mini-array into a larger array at intervals (not changing size)每隔一段时间将一个迷你数组插入一个更大的数组(不改变大小)
【发布时间】:2019-06-13 11:18:11
【问题描述】:

我试图在不调整大小的情况下将迷你数组插入到更大的数组中,因此使用迷你数组更改更大数组的值。

有一个迷你数组,xx。 有一个更大的数组,XX 每个 Y 元素,用迷你数组值替换下一个元素。 一路走到最后。

我尝试通过索引来做到这一点(代码可以在下面找到)。

mesh_array = np.zeros(shape=(100,100), dtype=np.uint8) 
mini_square = np.ones(shape=(2,2), dtype=np.uint8) 

flattened_array = np.ravel(mesh_array) 
flattened_minisquare = np.ravel(mini_square) 

flattened_array[1:-1:10] = flattened_minisquare

预期结果是每 10 个元素,它将用 flattened_minisquare 值替换以下元素。

[0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0...]

我得到的错误信息:

"ValueError: could not broadcast input array from shape (4) into shape (1000)"

【问题讨论】:

  • 演示将 (2,2) 插入 (10,10) 的样子
  • 这是我正在尝试的预期结果。类似的东西。

标签: python arrays numpy insert


【解决方案1】:

可能有更好的方法,但一种方法是按如下方式处理此问题:

import numpy as np

mesh_array = np.zeros(shape=(100,100), dtype=np.uint8) 
mini_square = np.ones(shape=(2,2), dtype=np.uint8) 

flattened_array = np.ravel(mesh_array) 
flattened_minisquare = np.ravel(mini_square)

现在,我们可以构造数组,该数组将对应于您希望用剩余值填充minisquare 的位置为零。请注意,如果给定的输出正确,在这种情况下它将是一个长度为 13 的数组。原始数组的 9 个元素 + minisquare 的 4 个元素

stepsize = 10
temp = np.zeros(stepsize + len(flattened_minisquare) - 1)
temp[-len(flattened_minisquare):] = flattened_minisquare

我们还为没有被小方块填充的值创建一个掩码。

mask = np.copy(temp)
mask[-len(flattened_minisquare):] = np.ones_like(flattened_minisquare)
mask = ~mask.astype(bool)

现在,只需使用np.resize 来扩展掩码和临时数组,然后最后使用掩码从旧数组中填充值。

out = np.resize(temp, len(flattened_array))
final_mask = np.resize(mask, len(flattened_array))
out[final_mask] = flattened_array[final_mask]

print(out)
#[0. 0. 0. ... 0. 0. 0.]

【讨论】:

  • 谢谢,这不是我想要的,但也很好用。非常感谢,祝你有美好的一天
  • @DenisD 如果你愿意,你可以澄清你想要什么。如果这与此处发布的示例输出有很大不同,您也可以发布另一个问题。如果答案对您没有用,您没有义务接受它。你到底想做什么?
  • 嗯,这对我也很有用,我最终弄清楚了我想要什么。不过,这非常不合时宜。这是我最初想要的,但是当我看到您的解决方案时,这也是可以接受的。 python x_axis = 11 y_axis = 15 test_array = np.zeros(shape=(x_axis, y_axis), dtype=np.uint8) for i in range(1, x_axis, 2): for j in range(1, y_axis, 2): test_array[i, j] = 1 print(test_array)
  • 啊,我明白了。很好地找到了一个可行的解决方案,很高兴听到!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 2021-12-28
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
相关资源
最近更新 更多