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
A_d_r_i
  • 21
  • 1
  • [Use slice objects to represent the slices](https://stackoverflow.com/questions/38917173/how-can-i-create-a-slice-object-for-numpy-array#57881698), store them in a list or array, and iterate over them? – Karl Knechtel Nov 26 '21 at 16:50
  • You should use the following: https://stackoverflow.com/questions/38917173/how-can-i-create-a-slice-object-for-numpy-array#57881698 –  Nov 26 '21 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 – jhylands Nov 26 '21 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. – hpaulj Nov 26 '21 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. – hpaulj Nov 27 '21 at 01:46

0 Answers0