Let's say I have an array r
of dimension (n, m)
. I would like to shuffle the columns of that array.
If I use numpy.random.shuffle(r)
it shuffles the lines. How can I only shuffle the columns? So that the first column become the second one and the third the first, etc, randomly.
Example:
input:
array([[ 1, 20, 100], [ 2, 31, 401], [ 8, 11, 108]])
output:
array([[ 20, 1, 100], [ 31, 2, 401], [ 11, 8, 108]])
With the help of numpy. random. shuffle() method, we can get the random positioning of different integer values in the numpy array or we can say that all the values in an array will be shuffled randomly. Return : Return the reshuffled numpy array.
Also, Using numpy. random. shuffle() function, we can shuffle the multidimensional array.
Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.
One approach is to shuffle the transposed array:
np.random.shuffle(np.transpose(r))
Another approach (see YXD's answer https://stackoverflow.com/a/20546567/1787973) is to generate a list of permutations to retrieve the columns in that order:
r = r[:, np.random.permutation(r.shape[1])]
Performance-wise, the second approach is faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With