I have a function that sometimes gives me a list of lists where the nested lists sometimes only have one item, such as this one:
a = [['1'], ['3'], ['w']]
And want to randomly select one item from that main list
a. If I try to use
np.random.choice on this list, I get a
ValueError: a must be 1-dimensional.
But if the list were instead:
b = [['1'], ['3'], ['w', 'w']]
np.random.choice works perfectly fine. Why is this? And how can I make it so that I can randomly select from both types of lists?
choice is first turning your list into an array.
In the second case, this array is a 1d array with dtype object:
In : np.array([['1'], ['3'], ['w', 'w']]) Out: array([['1'], ['3'], ['w', 'w']], dtype=object) In : _.shape Out: (3,)
In the second, it makes a 2d array of strings:
In : np.array([['1'], ['3'], ['w']]) Out: array([['1'], ['3'], ['w']], dtype='<U1') In : _.shape Out: (3, 1)
This is an issue that comes up periodically.
np.array tries to create as a high a dimensional array as the input allows.
Prevent numpy from creating a multidimensional array