1

I want to remap a numpy array according to a dictionary. Let us assume I have a numpy array with N rows and 3 columns. Now I want to remap the values according to its indices which are written in tuples in a dictionary. This works fine:

import numpy as np

a = np.arange(6).reshape(2,3)
b = np.zeros(6).reshape(2,3)
print a
print A

dictt = { (0,0):(0,2), (0,1):(0,1), (0,2):(0,0), (1,0):(1,2), (1,1):(1,1), (1,2):(1,0) }

for key in dictt:
    b[key] = a[dictt[key]]

print b
a = [[0 1 2]
    [3 4 5]]

b = [[ 2.  1.  0.]
    [ 5.  4.  3.]]

Let us assume I have N rows, where N is an even number. Now I want to apply the same mapping (which are valid for those 2 rows in the upper example) to all the other rows. Hence I want to have an array from:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

to:

b = [[ 2.  1.  0.]
    [ 5.  4.  3.]]
    [[ 8.  7.  6.]
    [ 11.  10.  9.]]

Any ideas? I would like to do it fast since these are 192000 entries in each array which should be remapped.

pallago
  • 419
  • 1
  • 4
  • 12
  • In python2 or python3 ? – alec_djinn Dec 01 '15 at 16:53
  • So the order that is defined in your dictionary is arbitrary? Or do you always want to mirror your data? Because there would be more efficient ways without using a dictionary then ... (numpy.fliplr) – elzell Dec 01 '15 at 17:04
  • Thanks fit the advices. It is Python 2.7. Unfortunately, the order is random not mirrored. – pallago Dec 02 '15 at 07:27

1 Answers1

0

For simplicity I would just use [::-1].

a = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
b = [item[::-1] for item in a]
>>> b
[[2, 1, 0], [5, 4, 3], [8, 7, 6]]
alec_djinn
  • 10,104
  • 8
  • 46
  • 71