Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in Python that shuffle data by data blocks?

For example, as to

[1 2 3 4 5 6]

Shuffle the data while keeping data blocks(including 2 data) as before. And we'll acquire:

[3 4 1 2 5 6]

Any way in Python to do this?

like image 684
jmir Avatar asked Sep 27 '17 12:09

jmir


3 Answers

A straightforward way to do this is using the following three steps:

  1. create blocks (a 2d-list);
  2. shuffle that list; and
  3. merge these lists again.

So:

import random

# Import data
data = [1,2,3,4,5,6]
blocksize = 2

# Create blocks
blocks = [data[i:i+blocksize] for i in range(0,len(data),blocksize)]
# shuffle the blocks
random.shuffle(blocks)
# concatenate the shuffled blocks
data[:] = [b for bs in blocks for b in bs]

If you do not want to store the data back in data, you can simply use:

data = [b for bs in blocks for b in bs]

For this data I obtained:

>>> data
[3, 4, 1, 2, 5, 6]

a second time:

>>> data
[5, 6, 1, 2, 3, 4]
like image 114
Willem Van Onsem Avatar answered Nov 11 '22 20:11

Willem Van Onsem


You can use the random module and call the function random.shuffle() - this will shuffle every element in your list, so break your list into sublists before shuffling

import random, itertools

mylist = [1, 2, 3, 4, 5, 6]
blocks = [mylist[x:x+2] for x in range(0, len(mylist), 2)]
random.shuffle(blocks)
list(itertools.chain.from_iterable(blocks))
>> [3, 4, 1, 2, 5, 6]
like image 33
AK47 Avatar answered Nov 11 '22 22:11

AK47


Somebody asked for a solution using numpy:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> np.random.shuffle(a.reshape((-1, 2)))
>>> a
array([5, 6, 3, 4, 1, 2])

This shuffles the reshaped view in place, but a keeps its original dimensions, so there's no need to reshape back.

like image 25
aerobiomat Avatar answered Nov 11 '22 22:11

aerobiomat