[英]Convert all zeros to ones which are between ones in numpy array
Consider a numpy array 考虑一个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]])
I want convert all zeroes to ones between ones 我想将所有零转换为1
output should be 输出应该是
[[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]]
How can I achieve this? 我该如何实现? Is there any numpy function to achieve that?
是否有任何numpy函数来实现?
Here's one approach using np.maximum.accumulate
by using it on a column-flipped version and without it and simply getting the intersection of them - 这是使用
np.maximum.accumulate
的一种方法,将其用于列翻转版本,如果没有,仅获取它们的交集-
def fill_gaps(arr):
ma = np.maximum.accumulate
return ma(arr[:,::-1],axis=1)[:,::-1] & ma(arr,axis=1)
Sample runs - 样品运行-
# 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]]
To fill for an array with 0s
and some other value say 255s
, here's a modification - 为了用
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)
Sample run - 样品运行-
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.