1

In my application, I have an array like this:

[10,20,30,
 40,50,60,
 70,80,90,

 0.1,0.2,0.3,
 0.4,0.5,0.6,
 0.7,0.8,0.9,

 1,2,3,
 4,5,6,
 7,8,9]

I want to reverse every 9 numbers so that my array looks like this:

[90,80,70,
 60,50,40,
 30,20,10,

 0.9,0.8,0.7,
 0.6,0.5,0.4,
 0.3,0.2,0.1,

 9,8,7,
 6,5,4,
 3,2,1]

Can someone tells me how to do this efficiently?

2 Answers 2

4

Perhaps something like:

n = a.shape[0]
a.reshape((n//9,9))[:,::-1].reshape((n,))

array([ 90. ,  80. ,  70. ,  60. ,  50. ,  40. ,  30. ,  20. ,  10. ,
        0.9,   0.8,   0.7,   0.6,   0.5,   0.4,   0.3,   0.2,   0.1,
        9. ,   8. ,   7. ,   6. ,   5. ,   4. ,   3. ,   2. ,   1. ])

But this relies on there being a multiple of 9 elements in your array. It leaves the original array unchanged. To alter the original a in-place you can use resize:

a.resize((n//9,9))
a[:,::-1] = a
a.resize((n,))
Sign up to request clarification or add additional context in comments.

Comments

0

This works. Not sure if it is the most effivient way:

  import numpy


  a = numpy.array([10,20,30,
   40,50,60,
   70,80,90,

   0.1,0.2,0.3,
   0.4,0.5,0.6,
   0.7,0.8,0.9,

   1,2,3,
   4,5,6,
   7,8,9])

  # reshape and transpose
  b = a.reshape(-1,9).T
  # reverse
  b = b[::-1]
  # convert back to flat array
  print b.T.flatten()
  # in one line
  print (a.reshape(-1,9).T[::-1].T).flatten()

Comments

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.