3

Suppose I have a list A and shuffled it:

import random
random.shuffle(A)

Now I with to shuffle the seconf list B with THE SAME permutation, as was applied by shuffle to A.

How is it possible?

What about pandas?

ayhan
  • 70,170
  • 20
  • 182
  • 203
Dims
  • 47,675
  • 117
  • 331
  • 600

3 Answers3

3

You could shuffle a list of indices:

import random

def reorderList(l, order):
    ret = []
    for i in order:
        ret.append(l[i])
    return ret

order = random.shuffle(range(len(a)))
a = reorderList(a, order)
b = reorderList(b, order)
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
2

With pandas, you would permute the index instead:

df = pd.DataFrame(np.random.choice(list('abcde'), size=(10, 2)), columns = list('AB'))

df
Out[39]: 
   A  B
0  c  e
1  b  e
2  c  e
3  a  d
4  e  d
5  d  d
6  b  b
7  a  e
8  e  b
9  a  b

Sampling with frac=1 gives you the shuffled dataframe:

df.sample(frac=1)
Out[40]: 
   A  B
6  b  b
5  d  d
1  b  e
2  c  e
9  a  b
8  e  b
4  e  d
7  a  e
3  a  d
0  c  e
ayhan
  • 70,170
  • 20
  • 182
  • 203
2

You could zip the lists before shuffling, then unzip them. It's not particularly memory efficient (since you're essentially copying the lists during the shuffle).

a = [1,2,3]
b = [4,5,6]

c = zip(a, b)
random.shuffle(c)

a, b = zip(*c)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118