gpt4 book ai didi

python - Numpy - 如何在发生变化的索引处移动值

转载 作者:行者123 更新时间:2023-11-30 22:04:11 26 4
gpt4 key购买 nike

所以我想在发生变化的一维 numpy 数组中移动我的值。配置移位样本。

input = np.array([0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,0,0,0,0])
shiftSize = 2
out = np.magic(input, shiftSize)
print out
np.array([0,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0])

例如,第一次切换发生且索引为 4,因此索引 2,3 变为“1”。下一次发生在 5,因此 6 和 7 变为“1”。

编辑:另外,没有 for 循环也很重要,因为这可能很慢(大数据集需要它)EDIT2:索引和变量名称

我尝试使用 np.diff,所以我知道发生更改的位置,然后使用 np.put,但是对于多个索引范围,这似乎是不可能的。

感谢您提前提供的帮助!

最佳答案

您想要的称为“binary dilation ”,包含在 scipy.ndimage 中:

import numpy as np
import scipy.ndimage

input = np.array([0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,0,0,0,0], dtype=bool)
out = scipy.ndimage.morphology.binary_dilation(input, iterations=2).astype(int)
# array([0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0])

关于python - Numpy - 如何在发生变化的索引处移动值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53396224/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com