Demonedge
Demonedge

Reputation: 1423

How to reverse sub arrays in numpy?

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?

Upvotes: 1

Views: 795

Answers (2)

xnx
xnx

Reputation: 25528

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,))

Upvotes: 4

Niemerds
Niemerds

Reputation: 942

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()

Upvotes: 0

Related Questions