1

Recently I learned some ways not to use for loops in numpy, since they make code inefficient and numpy enables you to work without for loops and more with lambda expressions.

So now I wonder if there is a possibility to do the following without any for loop, by creating some arrays before calculating:

Let's say I have an array with tuples:

slice_indexes = np.array([(0,9),(1,10),(2,11),(3,12),...])

Then we have an array we want to slice by those tuples:

data_array[i:j]

Is this achievable without a for loop? If yes? How?

user2853437
  • 750
  • 8
  • 27
  • Before I even review the code: "...numpy enables you to work without for loops and more with lambda expressions". Where does `lambda` come into this? You shouldn't be using `lambda`s with `numpy` unless absolutely necessary – roganjosh Jun 07 '20 at 18:13
  • Do all of your tuples contain the same size slice (in this case 9 elements)? Also what is the shape of your input array? – user3483203 Jun 07 '20 at 18:13
  • Would all slices have the same lengths? Like, in the given sample it's seems to be 9. – Divakar Jun 07 '20 at 18:19
  • If the resulting slices differ in size, then some sort of Python loop is necessary. Doubly so if the slices overlap. You can avoid loops only if the slicing pattern is regular, and can produce a 2d array. – hpaulj Jun 07 '20 at 18:28
  • yes. All slices would have the same length. – user2853437 Jun 07 '20 at 18:28
  • Would the starts be in that sequence as shown in the sample? Like we have 0,1,2,3 and so on here? – Divakar Jun 07 '20 at 18:31
  • @roganjosh Now I doubt that I got the right idea about lambda. But basically we used it a lot to write anonymous function calls. So it has maybe nothing do with writing efficient code. – user2853437 Jun 07 '20 at 18:32
  • @Divakar. Yes. As shown in the example. – user2853437 Jun 07 '20 at 18:33
  • Then, this should work for 1D array - https://stackoverflow.com/questions/40084931/. Can you confirm? – Divakar Jun 07 '20 at 18:33

0 Answers0