1

Edited my question to be more clear as I could not get the first answers to work.

I am trying to make a N-dimensional lookup table, from which to look up one value based on an input list of N True/False values.

For this I make an N-dimensional array, where each dimension has length 2 - one value for False (=0) and one for True (=1)

import numpy as np
import random
dims = 3
values = range(pow(2,dims))
lookup=np.reshape(values,np.tile(2,dims)) #this makes a 2x2x2x... array
condition=random.choices([True,False],k=dims) #this makes a 1d list of bools

the bools in condition should now specify the index to look up. As an example for N=3: if condition =(True,False,True), I want to get lookup[1,0,1].

Simply using

lookup[condition.astype(int)]

does not work, as numpy does not interpret the 1x3 array as index.

lookup[condition[0],condition[1],condition[2]]

works. But I havent figured out how to write this for N dimensions

1 Answers1

1

Manually converting it to a int-tuple allows the indexing you seek. Test the code below.

import numpy as np

# your example had d=3, but you may have something else.
# this is just creation of some random data...
d=3
answers = np.random.normal(size=[2] * d)
truth = tuple(np.random.choice([True, False], replace=True, size=d))

# manual conversion to int-tuple is needed, for numpy to understand that it
# is a indexing tuple.
# the box at the top of https://numpy.org/doc/stable/reference/arrays.indexing.html 
# says that tuple indexing is just like normal indexing, and in that case, we 
# need to have normal ints.
idx = tuple(int(b) for b in truth)
answer = answers[idx]
print(answer)
LudvigH
  • 3,662
  • 5
  • 31
  • 49