Randomizing 3 separate vector in the same order

Viewed 75

I want to randomize three separate vectors in python in the same order. I mean it in this way:

before randomizing:
a = [[1, ...],      b = [[1, ...],        c = [1, 
     [2, ...],           [2, ...],             2,
     [3, ...]]           [3, ...]]             3]

after randomizing:
a = [[2, ...],      b = [[2, ...],        c = [2, 
     [3, ...],           [3, ...],             3,
     [1, ...]]           [1, ...]]             1]

That's only an example how the data looks like. It's actually a big data set. I know that I could concatenate them and do the randomizing but is there any other way to do that without merging them, because I need them at the end to be separated.

3 Answers

One approach is to create an array of indexes, shuffle it, and then arrange the other arrays by it:

size = len(a)
indexes = np.arange(size)
new_a = np.empty(size)
new_b = np.empty(size)
new_b = np.empty(size)
for i in range(size):
    new_a[i] = a[indexes[i]]
    new_b[i] = b[indexes[i]]
    new_c[i] = c[indexes[i]]

You can randomize their indexes.

import numpy as np

# before randomizing:
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([1,2,3])

# randomize indexes
n = np.size(a,axis=0)
new_index = np.random.choice(n, size=n, replace=False)

# after randomizing (you may want a copy of them instead of a view):
a2 = a[new_index].copy()
b2 = b[new_index].copy()

Using the random generator apply the same seed before each shuffle operation.

import numpy as np

a = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])
b = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])
c = np.array([1, 2, 3])

SEED = 123456789

rng = np.random.default_rng(SEED)
rng.shuffle(a,axis=0)

rng = np.random.default_rng(SEED)
rng.shuffle(b,axis=0)

rng = np.random.default_rng(SEED)
rng.shuffle(c,axis=0)

Output from a, b and c

(array([[2, 3, 4, 5],
        [3, 4, 5, 6],
        [1, 2, 3, 4]]),
 array([[2, 3, 4, 5],
        [3, 4, 5, 6],
        [1, 2, 3, 4]]),
 array([2, 3, 1]))
Related