How to shuffle an array using Numpy?

To shuffle an array using Numpy, you can use the numpy.random.shuffle() function. Below is an example code demonstrating how to shuffle an array using Numpy.

import numpy as np

# 创建一个数组
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# 打乱数组
np.random.shuffle(arr)

# 打印打乱后的数组
print(arr)

The possible output could be:

[ 6  7  1 10  2  8  5  3  4  9]

Please note that the numpy.random.shuffle() function will modify the original array directly and will not return a new shuffled array. If you want to keep a copy of the original array, you can use the numpy.random.permutation() function.

import numpy as np

# 创建一个数组
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

# 打乱数组并返回一个新的打乱后的数组
shuffled_arr = np.random.permutation(arr)

# 打印打乱后的数组
print(shuffled_arr)

The possible output may be:

[10  3  6  1  9  2  8  7  5  4]

Here, a new shuffled array is generated using the numpy.random.permutation() function without altering the original array.

bannerAds