![](/img/trans.png)
[英]How do I convert an array of arrays consisting of 0s and 1s into a binary image?
[英]How can I replace 1s in a binary array with natural numbers, maintaining the position of 0s?
我正在使用Numpy和SciPy。 我有两个数组,第一个是二进制数组,第二个数组是从a
到b
的连续自然数范围,例如
mask = np.array([1, 1, 1, 1, 0, 0, 1, 0]) # length of 8, with 5 ones and 3 zeros
vals = np.array([2, 3, 4, 5, 6, 7, 8, 9]) # length of 8, only first 5 values will be used in this case - corresponding to the 5 ones in the first array
我想将第二个数组中的值替换为第一个数组中的1(按顺序保留),例如,本示例场景中所需的结果将是:
result = [2,3,4,5,0,0,6,0]
我已经用NumPy掩码数组和vectorise函数尝试了不同的方法。 我当前的解决方案如下,但是为了维持状态,我不得不引入一个全局变量!
global count
count = 0
def func(a,b):
global count
if a ==1:
return b - count
else:
count +=1
return 0
v_func = np.vectorize(func)
result = v_func(mask, vals)
print result
有没有更优雅的方法(理想情况下使用NumPy)呢?
(请注意,我正在使用的实际数组非常大,因此我的解决方案需要对消耗的内存量敏感-显然我可以转换为稀疏数组,但是我仍然遇到几次内存错误试图找到不同的解决方案。)
这是一种方法:
In [15]: result = np.zeros_like(vals)
In [16]: result[mask > 0] = vals[:mask.sum()]
In [17]: result
Out[17]: array([2, 3, 4, 5, 0, 0, 6, 0])
这是一个衬板,尽管我必须说这不是一种优化的方法,也不是很优雅。 但是您可以出于实践目的对其进行检查。
a = [1, 1, 1, 1, 0, 0, 1, 0]
b = [2, 3, 4, 5, 6, 7, 8, 9]
c = [b[sum(a[:i])] if a[i] else 0 for i in range(len(a))]
print c
# Gives [2, 3, 4, 5, 0, 0, 6, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.