Search code examples
pythonarraysnumpyshuffle

Shuffling numpy arrays keeping the respective values


I have two numpy arrays, both with 1 million spaces, and all the values inside the first one have a corresponding value with the values in the second one. I want to shuffle both of them while keeping the respective values. How do I do that?


Solution

  • Since both arrays are of same size, you can use Numpy Array Indexing.

    def unison_shuffled_copies(a, b):
        assert len(a) == len(b)                  # don't need if we know array a and b is same length
        p = numpy.random.permutation(len(a))     # generate the shuffled indices
        return a[p], b[p]                        # make the shuffled copies using same arrangement according to p
    

    This is referencing this answer, with some changes.