Unfortunately, I often have while loops in my Python code that cause my programs to slow down significantly.
The following is an example of a while loop (shape = (1000,1000,3)
):
i = 0
j = 0
while i < arr.shape[0]:
while j < arr.shape[1]:
if arr[i,j,0] <= 5 and arr[i,j,0] > 0:
arr[i,j,:] = 1
else:
arr[i,j,:] = 0
j = j + 1
j = 0
i = i + 1
-->
def f(x):
return 1 if x <= 5and x > 0 else 0
f = np.vectorize(f)
arr= f(arr)
EDIT: another while loop
i = 0
j = 0
while i < arr1.shape[0]:
while j < arr1.shape[1]:
if arr1[i, j, 0] == 0 and arr1[i, j, 1] == 0 and arr1[i, j, 2] == 0:
arr1[i, j, :] = arr1[i, j, :]
else:
arr1[i, j, :] = arr2[i, j, :]
j = j + 1
j = 0
i = i + 1
Is there a way to speed things up? I'm not sure how.