Map numpy array using dict?

Viewed 401

I have a potentially long array of one's and zero's that looks like this: a = [0,0,1,0,1,0,.....] I want to translate each consecutive pair of values to an integer between 0 & 3 as shown below:

  • 0,0 -> 0
  • 0,1 -> 1
  • 1,0 -> 3
  • 1,1 -> 2

I'm looking for a nice clean efficient way to create the array b (example output below) using the mapping above: b = [0, 3, 3,...]

Is a dict a good idea? I can't figure out how to do it though.

3 Answers

Try:

x = np.reshape(a, (-1,2))

b = x[:,0]*2 + (x[:,0] ^ x[:,1])

You could use the successive pairs as indices to perform a look-up, for getting the translated value:

master = np.array([[0, 1],[3, 2]])
b = master[a[::2], a[1::2]]

Test input:

[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1]

Output:

[2, 1, 2, 2, 1, 1, 0, 3]

If you want to use a dict with an explicit mapping between corresponding decimal numbers, you could try this:

# Convert to a (-1,2) matrix and decimal numbers first
a = np.reshape(a, (-1,2))
a = np.sum(np.array([2,1])*a, axis=1)

# Define dictionary with mapping
D = {0: 0, 1: 1, 2: 3, 3: 2}

# Apply dictionary
a = [D[x] for x in a]
Related