Skip to content
Advertisement

Element-wise random choice of a Series of lists (without a loop)

I want to randomly select an element from each list in a Series of lists.

JavaScript

So s is:

JavaScript

I know I can do the following:

JavaScript

Which does work:

JavaScript

But I am wondering if there is a non-loop approach to do this?

For instance, (assuming each list is equal size) you could make an array of random indices to try and pick a different element from each list:

JavaScript

But doing say s[i] doesn’t work because that is indexing s rather than applying to each list:

JavaScript

My motivation is to have something that would work on a large amount of lists, hence the avoidance of a loop. But if my list comprehension seems like the most reasonable, or there is no builtin pandas/numpy function for this, please tell me.

Advertisement

Answer

I can only think of this way , however, the performance may be the problem

JavaScript

Some timing

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement