0

Is there an efficient way to access multiple slices of an array with a flexible number of slices ? Example below with a for loop I would like to avoid, left and right arrays lenghts are variable...

a = np.array([0,1,2,3,4,5,6,7,8,9]) 
left =np.array([0,5])
right = np.array([2,8])   
for i in range(len(left)):
   a[left[i]:right[i]] = -1
5
  • Use slice objects to represent the slices, store them in a list or array, and iterate over them? Commented Nov 26, 2021 at 16:50
  • You should use the following: stackoverflow.com/questions/38917173/… Commented Nov 26, 2021 at 16:51
  • If the operation inside the loop was more taxing I would say generate the minimum set of slices so you aren't resetting elements you already covered Commented Nov 26, 2021 at 16:51
  • Those slices are discontinuous, so can't be represented as a single slice. If you convert them to an array of indices, e.g. array([0, 1, 5, 6, 7]), you can get by with just one indexing operation. But creating that array will be as expensive iterating on the slices. Unless the slice lengths all match. Commented Nov 26, 2021 at 17:27
  • np.r_[tuple([slice(i,j) for i,j in zip(left,right)])] produces array([0, 1, 5, 6, 7]). It expands the slices into arange arrays and concatenates them. It's proposed more for convenience than speed. Commented Nov 27, 2021 at 1:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.