0

Let us assume the following example:

import numpy as np
x = np.random.random([100,200,300,400])
c1 = np.arange(0,100,17)
c2 = np.arange(0,100,17)
c3 = np.arange(0,100,17)
c4 = np.arange(0,100,17)
q = (((x[c1,:,:,:])[:,c2,:,:])[:,:,c3,:])[:,:,:,c4]

which is the most inefficient way after looking at this and this, these are telling me that it would be good idea to unravel the 4d array into 1d and then index only in one dimension. So, is there not a better way to achieve what I am trying to achieve?

Community
  • 1
  • 1
varantir
  • 6,624
  • 6
  • 36
  • 57

1 Answers1

1

You could use np.ix_ to build the appropriate indices:

>>> %timeit q = (((x[c1,:,:,:])[:,c2,:,:])[:,:,c3,:])[:,:,:,c4]
1 loops, best of 3: 237 ms per loop
>>> %timeit q = x[np.ix_(c1, c2, c3, c4)]
100000 loops, best of 3: 19.3 µs per loop

which is orders of magnitude faster but gives the same result:

>>> np.allclose((((x[c1,:,:,:])[:,c2,:,:])[:,:,c3,:])[:,:,:,c4], x[np.ix_(c1, c2, c3, c4)])
True
DSM
  • 342,061
  • 65
  • 592
  • 494