3

I have a numpy array that looks like the following [-1,0,1,0,1,2,1,2,3,...,n-1,n,n+1,n,n+1,n+2..] I would like to shuffle the array in chunks of 3, is there an efficient way to do it in numpy?

I know you can shuffle a numpy array using the following shuffle method, but this gives me a fully shuffled array. Is there a way to shuffle it in chunks in numpy?

import numpy.random as rng

ind = numpy.arange(100)
rng = numpy.random.RandomState(123)
rng.shuffle(ind)

1 Answer 1

8

Reshape into 3 columns. shuffle doc says it just shuffles the 1st dimension:

ind=np.arange(99)  # multple of 3
ind=ind.reshape(-1,3)
rng.shuffle(ind)
ind.flatten()
Sign up to request clarification or add additional context in comments.

2 Comments

To keep the array flattened after the process, shouldn't the last operation be ind = ind.flatten()?
Right. flatten isn't an inplace operation. I adapted the code snippet from an interactive session, where I got an automatic print of the last line.

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.