Aayush
Aayush

Reputation: 124

Set all values between 2 ranges in numpy array to certain value

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?

Upvotes: 2

Views: 647

Answers (1)

mozway
mozway

Reputation: 262484

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]])

Upvotes: 4

Related Questions