0

Im currently trying to implement a replay buffer, in which i store 20 numbers in a list and then want to sample 5 of these numbers randomly.

I tried the following with numpy arrays:

ac = np.zeros(20, dtype=np.int32)

for i in range(20):
    ac[i] = i+1

batch = np.random.choice(20, 5, replace=False)
sample = ac[batch]

print(sample)

This works the way it should, but i want the same done with a list instead of a numpy array.

But when i try to get sample = ac[batch] with a list i get this error message:

TypeError: only integer scalar arrays can be converted to a scalar index

How can i access multiple elements of a list like it did with numpy?

Ronnee
  • 21
  • 1
  • Does this answer your question? [Python: Select subset from list based on index set](https://stackoverflow.com/questions/3179106/python-select-subset-from-list-based-on-index-set) – ScootCork Jan 04 '21 at 11:33

1 Answers1

0

For a list it is quite easy. Just use the sample function from the random module:

import random

ac = [i+1 for i in range(20)]
sample = random.sample(ac, 5)

Also on a side note: When you want to create a numpy array with a range of numbers, you don't have to create an array with zeros and then fill it in a for loop, that is less convenient and also significantly slower than using the numpy function arange.

ac = np.arange(1, 21, 1)

If you really want to create a batch list that conaints the indexes you want to access, then you will have to use a list comprehension to access those, since you cant just index a list with multiple indexes like a numpy array.

batch = [random.randint(0, 20) for _ in range(5)]
sample = [ac[i] for i in batch]
sunnytown
  • 1,844
  • 1
  • 6
  • 13
  • Thanks for the side note, i will remember that. But i cant use your solution as I have saved mutliple variables which get sampled. And i need their indexes to match, so if i sample 5 random numbers from ac i would need the the values of another variable at the same indeces – Ronnee Jan 04 '21 at 11:23
  • Take a look at my last edit. This is how you can select the elements from one list based on a list of indexes. You can repeat that process for multiple lists from which you want to select the values at the indexes stored in batch. – sunnytown Jan 04 '21 at 11:25