7

I have a list of lists, where each list is associated with a score/weight. I want to produce a new list of lists by randomly selecting from the first one so that those with higher scores will appear more often. The line below works fine when population is just a normal list. But I want to have it for a list of lists.

population = [['a','b'],['b','a'],['c','b']]
list_of_prob = [0.2, 0.2, 0.6]

population = np.random.choice(population, 10, replace=True, p=list_of_prob)

This will give the output ValueError: a must be 1-dimensional

1
  • @Chicony you should mention in the question that it's not necessary should be numpy Commented Oct 11, 2016 at 9:06

1 Answer 1

10

Instead of passing the actual list, pass a list with indexes into the list.

np.random.choice already allows this, if you pass an int n then it works as if you passed np.arange(n).

So

choice_indices = np.random.choice(len(population), 10, replace=True, p=list_of_prob)
choices = [population[i] for i in choice_indices]
Sign up to request clarification or add additional context in comments.

6 Comments

TypeError: only integer arrays with one element can be converted to an index
@roganjosh use range(len(population))
This will actually work like a charm, just if you do choice = [population[i] for i in choice_index], instead of choice = population[choice_index] as choice_index is a list
@SardorbekImomaliev still the same error. It comes from line choice = population[choice_index]
@roganjosh: sorry, I didn't notice you were getting 10 values, assumed 1. Will edit.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.