What is the best way to perform an anti-transpose in python?
Asked Answered
E

4

15

Lets say I have an array

a = np.arange(16).reshape((4,4))

0   1  2   3
4   5  6   7
8   9  10  11
12  13 14  15

But I want

15  11  7  3
14  10  6  2
13  9   5  1
12  8   4  0

which is a flip across the secondary diagonal, or a kind of anti-transpose.

How can I do this in numpy?

Evanevander answered 27/6, 2017 at 4:50 Comment(3)
Have you attempted anything or are you simply getting your homework done by us...Fortissimo
@VaibhavBajaj self-answered questionCummings
@AnttiHaapala :O Oops. Didn't see that.Fortissimo
E
19

One could do one of the following:

rot90(a,2).T

rot90(flipud(a),1)

rot90(fliplr(a), -1)

or as hpaulj suggested in the comments (thanks hpaulj)

a[::-1,::-1].T

Here are the speed rankings as ratios of the slowest method after anti-transposing 1000 random 10000x10000 arrays.

  1. 63.5% - a[::-1,::-1].T
  2. 85.6% - rot90(a,2).T
  3. 97.8% - rot90(flipud(a),1)
  4. 100% -rot90(fliplr(a),-1)
Evanevander answered 27/6, 2017 at 4:50 Comment(3)
I'm hoping someone knows a secret numpy way of doing this.Evanevander
a[::-1,::-1].T; this is a view, sharing the same data buffer, so it will be as fast as possible. To test for view, try changing one element and see if it changes the original. The double reverse slice is the same as np.rot90(a,2). Look at it's code.Excel
@Excel so you should add that as an answerCummings
T
2

np.flip(a).T

From the np.flip documentation & @hpaulj 's comment:

flip(m) corresponds to m[::-1,::-1,...,::-1] with ::-1 at all positions.

Tome answered 29/9, 2022 at 5:39 Comment(0)
A
1

Here's another to throw into the mix.

a.ravel('F')[::-1].reshape(a.shape)
Aphasic answered 27/6, 2017 at 6:39 Comment(2)
Although I like this because of ravel, its also about 200x slower than rot90(fliplr(a),-1). :/Evanevander
No worries, I was just exploring other ways of doing it (-:Aphasic
H
0

Try it in this manner,

np=np[::-1] #reverse the array
a = np.arange(16).reshape((4,4))
Horsefly answered 27/6, 2017 at 7:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.