This is hard to explain but I have a list of tuples where every tuple is length n and the possible values of the items in each tuple are contained in a set of lists (one list for each position in the tuple).
For the sake of a simple example, my list of tuples might be
sequence = [('b', 1), ('c', 2), ('c', 1), ('a', 3), ('c', 2), ('a', 3)]
The lists of possible values are:
state_lists = [['a', 'b', 'c'], [1, 2, 3, 4]]
I want an efficient way to create a list or array (integer array preferred) similar to sequence but with each value replaced by its index in the appropriate list from state_lists .
Here is one solution which utilizes np.searchsorted. Unfortunately, this function only supports 1-D arrays:
import numpy as np
sequence_as_array = np.array(sequence)
sequence_indexes = [
np.searchsorted(states, sequence_as_array[:, i])
for i, states in enumerate(state_lists)
]
lookup_array = np.vstack(sequence_indexes).T
print(lookup_array)
[[1 0]
[2 1]
[2 0]
[0 2]
[2 1]
[0 2]]
Is there a simpler way to do this (e.g. without a for loop, conversion of sequence to an array and avoiding the vstack)?
It must be a general solution as the length of the tuples could be more than 2 and the data types could be float, int or string.
The reason for replacing the values is to create a lookup array for fast indexing and less memory than storing the original values. The length of sequence could be over 10,000.