First, you need know what the categories are. set(iterable) is a convenient method.
Then, np.where can tell all the indexes of a certain object in the array.
Finally, chooseone randomly from the indexes for each category.
import random
import numpy as np
def random_index_each(array):
def random_index(item):
return (item, random.choice(np.where(array == item)[0]))
return dict(map(random_index, set(array)))
if __name__ == '__main__':
array = np.array([2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1, 0, 1, 0, 0, 2, 2, 1])
for _ in range(4):
print(random_index_each(array))
Output:
{0: 16, 1: 12, 2: 8}
{0: 15, 1: 14, 2: 6}
{0: 15, 1: 19, 2: 6}
{0: 15, 1: 11, 2: 2}
If you do not care about from which category the index gets picked, you can use a list to restore the result. Or let it exist in form of an iterable object.