To shuffle a NumPy array, you can use the numpy.random.shuffle() function. This function shuffles the array in place (i.e., it modifies the original array), randomly rearranging the elements along the first axis (for multi-dimensional arrays, it shuffles the rows).
Syntax:
python
Copy code
numpy.random.shuffle(arr)
arr: The NumPy array to be shuffled (this is modified in place).
Examples
1. Shuffle a 1D Array
python
Copy code
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
Shuffle the array in place
np.random.shuffle(arr)
print("Shuffled 1D Array:", arr)
Output:
python
Copy code
Shuffled 1D Array: [30 10 50 40 20] # (Output will vary every time)
2. Shuffle a 2D Array (Rows)
For a 2D array, numpy.random.shuffle() will shuffle the rows along the first axis. It does not shuffle elements within individual rows.
python
Copy code
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Shuffle the rows in place
np.random.shuffle(arr_2d)
print("Shuffled 2D Array (Rows):\n", arr_2d)
Output:
python
Copy code
Shuffled 2D Array (Rows):
[[7 8 9]
[1 2 3]
[4 5 6]] # (Output will vary every time)
3. Shuffle a 2D Array (Elements within the Array)
If you want to shuffle all elements in the array, you can first flatten the array and then shuffle it.
python
Copy code
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Flatten the array, shuffle, then reshape back to the original shape
arr_2d_flat = arr_2d.flatten()
np.random.shuffle(arr_2d_flat)
arr_2d_shuffled = arr_2d_flat.reshape(arr_2d.shape)
print("Shuffled 2D Array (Elements):\n", arr_2d_shuffled)
Output:
python
Copy code
Shuffled 2D Array (Elements):
[[7 1 5]
[3 2 9]
[4 6 8]] # (Output will vary every time)
4. Shuffle without modifying the original Array (using numpy.random.permutation)
If you want to shuffle the array but keep the original array intact, use numpy.random.permutation(). It returns a new shuffled array without modifying the original one.
python
Copy code
arr = np.array([10, 20, 30, 40, 50])
Create a shuffled version of the array without modifying the original
shuffled_arr = np.random.permutation(arr)
print("Original Array:", arr)
print("Shuffled Array:", shuffled_arr)
Output:
python
Copy code
Original Array: [10 20 30 40 50]
Shuffled Array: [30 10 50 40 20] # (Output will vary every time)
Summary:
Use np.random.shuffle(arr) to shuffle the array in place.
Use np.random.permutation(arr) to shuffle the array without modifying the original array.
For a 2D array, np.random.shuffle() shuffles the rows, not the individual elements.
To shuffle all elements of a 2D array, flatten the array first, shuffle, then reshape it back.
Let me know if you need more details or examples!
Информация по комментариям в разработке