0

I have list of arrays similar to lstB and want to pick random collection of 2D arrays. The problem is that numpy somehow does not treat objects in lists equally:

lstA = [numpy.array(0), numpy.array(1)]
lstB = [numpy.array([0,1]), numpy.array([1,0])]

print(numpy.random.choice(lstA))   # returns 0 or 1
print(numpy.random.choice(lstB))   # returns ValueError: must be 1-dimensional

Is there an ellegant fix to this?

4
  • Any reason not to use the std. lib. random.choice function rather than NumPy's? Alternatively, you could use np.random.randint to generate a suitable index. Commented Nov 23, 2017 at 20:09
  • It is possible, but not convenient for more than one element to pick. Commented Nov 23, 2017 at 20:17
  • If you want to pick an object from a list, random.choice is the obvious choice. numpy.random.choice is for sampling from 1-dimensional arrays. Commented Nov 23, 2017 at 21:28
  • Do you want to pick with replacement or without replacement? Commented Nov 24, 2017 at 0:27

1 Answer 1

1

Let's call it semi-elegant...

# force 1d object array
swap = lstB[0]
lstB[0] = None
arrB = np.array(lstB)
# reinsert value
arrB[0] = swap
# and clean up
lstB[0] = swap
# draw
numpy.random.choice(arrB)
# array([1, 0])

Explanation: The problem you encountered appears to be that numpy when converting the input list to an array will make as deep an array as it can. Since all your list elements are sequences of the same length this will be 2d. The hack shown here forces it to make a 1d array of object dtype instead by temporarily inserting an incompatible element.

However, I personally would not use this. Because if you draw multiple subarrays with this method you'll get a 1d array of arrays which is probably not what you want and tedious to convert.

So I'd actually second what one of the comments recommends, i.e. draw ints and then use advanced indexing into np.array(lstB).

Sign up to request clarification or add additional context in comments.

Comments

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.