title: Roll of different amount along a single axis in a 3D matrix
body: <p>I have a <strong>cube</strong> of shape (x,y,t). I need to shift each (x,y) indices of a varying number of position <strong>along the t axis</strong>. Basically I have something like:</p>
  
  <pre><code>roll_matrix = [[0,5,9,0], [3,2,0,0]]
  </code></pre>
  
  <p>The roll_matrix specifies, for each (x,y) position how much to shift along the remaining axis <strong>(axis=2)</strong>. I never need to roll along other axis.</p>
  
  <p>For example, cube[1,0] must shift 3 position, cube [0,0] must stay as-is, etc. I don't care too much what happens with the rolled values - ideally just move them form the front to the end of the array along the time axis. But I could pad with neutral values, in case some slicing notation would do the trick.</p>
  
  <p>I care more about speed than what happens with rolled over values, in other words.</p>
  
  <p>I currently have a for-loop that takes forever. I need an optimized notation to accomplish this instead. I looked up numpy.roll(), however it only allows you to roll along more than one axis, not to perform different roll values along the same one....</p>
  
  <p>Any ideas?</p>
  
  <p>EDIT: </p>
  
  <p>The current for loop:</p>
  
  <pre><code>import numpy as np
  
  cube = np.linspace(0,39,40)
  cube = cube.reshape((2,2,10))
  roll_matrix = np.array([[4,0],[3,2]])
  print(cube)
  print("")
  def roll(cube, roll_matrix):
      cp_cube = np.copy(cube)
      Rawf = cube.reshape(cube.shape[0] * cube.shape[1], cube.shape[2])
      ThPosf = roll_matrix.reshape(roll_matrix.shape[0] * roll_matrix.shape[1])
  
      RawThf = Rawf
      for i, trigger_value in enumerate(ThPosf):
          RawThf[i, :] = np.roll(Rawf[i, :], -trigger_value)
  
      RawTh = RawThf.reshape(cube.shape[0], cube.shape[1], cube.shape[2])
      return RawTh
  
  ans = roll(cube, roll_matrix)
  print(ans)
  </code></pre>
  
  <p>While yields:</p>
  
  <p>Initial data:</p>
  
  <pre><code>[[[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
    [10. 11. 12. 13. 14. 15. 16. 17. 18. 19.]]
  
   [[20. 21. 22. 23. 24. 25. 26. 27. 28. 29.]
    [30. 31. 32. 33. 34. 35. 36. 37. 38. 39.]]]
  </code></pre>
  
  <p>Rolled data:</p>
  
  <pre><code>[[[ 4.  5.  6.  7.  8.  9.  0.  1.  2.  3.]     #shifted 4
    [10. 11. 12. 13. 14. 15. 16. 17. 18. 19.]]    # no shift, 0
  
   [[23. 24. 25. 26. 27. 28. 29. 20. 21. 22.]     #shifted 3
    [32. 33. 34. 35. 36. 37. 38. 39. 30. 31.]]]   # 2
  </code></pre>
  
  <p><code>roll_matrix</code> isn't being used other than here - it's the output from a calculation that tells me how much each to move to be aligned along the time axis. Basically the data obtained is misaligned and I need to align them properly along the time axis.</p>