Issue
I have 2 1d arrays of type int and a start and a stop value that look like this:
y_start = #some number
y_end = #some number
x_start = #some array of ints
x_end = #some array of ints
What I want is to simulate the following behavior without loops:
for i, y in enumerate(range(y_start, y_end)):
arr[x_start[i]:x_end[i], y] = c
Example:
y_start = 2
y_end = 5
x_start = np.array([2, 1, 3])
x_end = np.array([4, 3, 6])
c = 1
Input
arr = array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]])
Output:
arr = array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0]])
Would this be possible?
Solution
You can use indexing and a crafted boolean arrays converted to integer:
v = np.arange(arr.shape[0])[:,None]
# conversion to int is implicit
arr[:, y_start:y_end] = ((v>=x_start) & (v<x_end))#.astype(int)
output:
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0]])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.