Search code examples
pythonpandasloopsindexing

How to pop randomised items from a list in a loop


I have a file containing experimental parameters where each row is a different trial & each column is a separate parameter for the experiment such that a different combination of parameters such as sound & text is chosen at each trial eg. 'Sound': blue, 'Text': red etc.

These parameters are stored in a csv & opened using pandas:

parameters = pd.read_csv('Parameters.csv')
Sound_list = parameters['Sound']
Text_list = parameters['Text']

The for loop is iterating through an experimental loop in Psychopy (not the parameters list itself) but even using the following I can't get it to work.

for i in range(0,10):
    n = range(0,len(Sound_list),1)
    index = random.choice(n)
    Sound_to_play = Sound_list.pop(index)
    Text_to_show = Text_list.pop(index)

I am trying to pop each trial from the list such that each combination is shown the same number of times however I get the following error:

 Traceback (most recent call last):

  File "<ipython-input-4-9fe2444288e3>", line 4, in <module>
    Sound_to_play = Sound_list.pop(index)

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 790, in pop
    result = self[item]

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/series.py", line 871, in __getitem__
    result = self.index.get_value(self, key)

  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 4405, in get_value
    return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))

  File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value

  File "pandas/_libs/index.pyx", line 90, in pandas._libs.index.IndexEngine.get_value

  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 997, in pandas._libs.hashtable.Int64HashTable.get_item

  File "pandas/_libs/hashtable_class_helper.pxi", line 1004, in pandas._libs.hashtable.Int64HashTable.get_item

KeyError: 0

Does anyone know how to fix this? Thank you!


Solution

  • Like mentioned above, you do not have a list. The second thing you have to consider is, that:

    random.choice(n)

    takes a seq as input parameter. So in that case you can write:

    parameters = pd.read_csv('Parameters.csv')
    Sound_list = [n for n in parameters['Sound'].values]
    Text_list = [n for n in parameters['Text'].values]
    

    and then run your loop with:

    for i in range(0,10):
        index = random.choice(Sound_list)
        Sound_to_play = Sound_list.pop(index)
        Text_to_show = Text_list.pop(index)