考虑一个numpy数组
arr = numpy.array([[1,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,1,1,1,1,1,1,1,1],
[1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
[0,0,0,0,0,1,0,1,1,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0]])
我希望将所有零转换为1之间的零
输出应该是
[[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0]]
我怎样才能做到这一点?是否有任何numpy功能来实现这一目标?
答案 0 :(得分:2)
这是一种使用np.maximum.accumulate
的方法,通过在列翻转版本上使用它而没有它并简单地获取它们的交集 -
def fill_gaps(arr):
ma = np.maximum.accumulate
return ma(arr[:,::-1],axis=1)[:,::-1] & ma(arr,axis=1)
样品运行 -
# Sample #1
In [27]: print arr
[[1 0 1 0 1 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 1 1 1]
[1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
[0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0]]
In [28]: print fill_gaps(arr)
[[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0]]
# Sample #2
In [42]: print arr
[[1 0 1 0 1 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 1 1 1]
[0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0]
[0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0]]
In [43]: print fill_gaps(arr)
[[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0]
[0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0]]
要填充0s
的数组以及其他一些值255s
的数组,这里有一个修改 -
def fill_gaps(arr, value=1):
ma = np.maximum.accumulate
mask = arr==value
mask_filled = ma(mask[:,::-1],axis=1)[:,::-1] & ma(mask,axis=1)
return np.where(mask_filled,value,0)
示例运行 -
In [69]: print arr
[[255 0 255 0 255 0 255 0 0 0 0 255 0 0 0 0 0 0
0 255 0 0 255 255 255 255 255 255 255 255]
[ 0 0 0 255 0 255 0 255 0 255 0 255 0 255 0 255 0 255
0 255 0 255 0 255 0 255 0 255 0 0]
[ 0 0 0 0 0 255 0 255 255 255 255 255 0 0 0 255 255 255
0 0 0 0 0 0 0 0 0 0 0 0]]
In [70]: print fill_gaps(arr, 255)
[[255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255]
[ 0 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 0 0]
[ 0 0 0 0 0 255 255 255 255 255 255 255 255 255 255 255 255 255
0 0 0 0 0 0 0 0 0 0 0 0]]