Python Numpy-如何在发生更改的索引处移动值

Python Numpy-如何在发生更改的索引处移动值,python,numpy,Python,Numpy,所以我想在一维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点,所以

所以我想在一维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 cycle也很重要,因为这可能会很慢(对于大型数据集来说是必需的) EDIT2:索引和变量名

我尝试了np.diff,所以我得到了变化发生的位置,然后是np.put,但是使用多个索引范围似乎是不可能的

提前感谢您的帮助

您想要的称为“”,包含在
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])

尼尔斯的答案似乎不错。以下是仅使用NumPy的替代方案:

import numpy as np

def dilate(ar, amount):
    # Convolve with a kernel as big as the dilation scope
    dil = np.convolve(np.abs(ar), np.ones(2 * amount + 1), mode='same')
    # Crop in case the convolution kernel was bigger than array
    dil = dil[-len(ar):]
    # Take non-zero and convert to input type
    return (dil != 0).astype(ar.dtype)

# Test
inp = np.array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0])
print(inp)
print(dilate(inp, 2))
输出:

[0 0 0 1 0 0 0 0 0 0 1 1 0 0 1 0 0 0 0 0 0 0]
[0 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0]

另一个numpy解决方案:

def dilatation(seed,shift):
out=seed.copy()
for sh in range(1,shift+1):
    out[sh:] |= seed[:-sh]
for sh in range(-shift,0):
    out[:sh] |= seed[-sh:]
return out
示例(shift=2):


中的
不是有效的变量名,并且numpy中没有
magic
。索引
2,3
,或者索引
2
3
?为什么4导致设置/切换2,3,而5设置/切换5和6?值是否设置为1,或在0和1之间切换,反之亦然?现在还不清楚你的逻辑是什么。这只是为了演示,但却是真的!对于已编辑的索引,我只是键入了一些。我仍然不明白为什么索引4会切换它前面的两个索引,而f会切换它后面的两个索引。还不清楚指数是否被切换,或者仅仅设置为1(即使已经是1)。
in : [0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0]
out: [0 0 0 0 0 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1]