回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>给定一个2D numpy数组:</p>
<pre><code>00111100110111
01110011000110
00111110001000
01101101001110
</code></pre>
<p>有没有一种有效的方法来替换长度为<code>1</code>的运行?在</p>
<p>例如,如果<code>N=3</code></p>
^{pr2}$
<p>实际上,2D数组是二进制的,我想用0代替1的运行,但是为了清楚起见,我在上面的例子中用2替换它们。在</p>
<p><strong>可运行示例:<a href="http://runnable.com/U6q0q-TFWzxVd_Uf/numpy-replace-runs-for-python" rel="nofollow">http://runnable.com/U6q0q-TFWzxVd_Uf/numpy-replace-runs-for-python</a></strong></p>
<p>我目前使用的代码看起来有点老套,我觉得可能有一些神奇的纽姆方法来做到这一点:</p>
<p><strong>更新:</strong>我知道我将示例更改为不处理转角情况的版本。这是一个小的实现错误(现在已修复)。我更感兴趣的是有没有一种更快的方法来做这件事。在</p>
<pre><code>import numpy as np
import time
def replace_runs(a, search, run_length, replace = 2):
a_copy = a.copy() # Don't modify original
for i, row in enumerate(a):
runs = []
current_run = []
for j, val in enumerate(row):
if val == search:
current_run.append(j)
else:
if len(current_run) >= run_length or j == len(row) -1:
runs.append(current_run)
current_run = []
if len(current_run) >= run_length or j == len(row) -1:
runs.append(current_run)
for run in runs:
for col in run:
a_copy[i][col] = replace
return a_copy
arr = np.array([
[0,0,1,1,1,1,0,0,1,1,0,1,1,1],
[0,1,1,1,0,0,1,1,0,0,0,1,1,0],
[0,0,1,1,1,1,1,0,0,0,1,0,0,0],
[0,1,1,0,1,1,0,1,0,0,1,1,1,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,0,0],
[1,1,1,1,1,1,1,1,1,1,1,1,1,0],
[0,1,1,1,1,1,1,1,1,1,1,1,1,1],
])
print arr
print replace_runs(arr, 1, 3)
iterations = 100000
t0 = time.time()
for i in range(0,iterations):
replace_runs(arr, 1, 3)
t1 = time.time()
print "replace_runs: %d iterations took %.3fs" % (iterations, t1 - t0)
</code></pre>
<p>输出:</p>
<pre><code>[[0 0 1 1 1 1 0 0 1 1 0 1 1 1]
[0 1 1 1 0 0 1 1 0 0 0 1 1 0]
[0 0 1 1 1 1 1 0 0 0 1 0 0 0]
[0 1 1 0 1 1 0 1 0 0 1 1 1 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 0 0]
[1 1 1 1 1 1 1 1 1 1 1 1 1 0]
[0 1 1 1 1 1 1 1 1 1 1 1 1 1]]
[[0 0 2 2 2 2 0 0 1 1 0 2 2 2]
[0 2 2 2 0 0 1 1 0 0 0 2 2 0]
[0 0 2 2 2 2 2 0 0 0 1 0 0 0]
[0 1 1 0 1 1 0 1 0 0 2 2 2 0]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0]
[2 2 2 2 2 2 2 2 2 2 2 2 2 0]
[0 2 2 2 2 2 2 2 2 2 2 2 2 2]]
replace_runs: 100000 iterations took 14.406s
</code></pre>