filmov
tv
how to shuffle numpy array

Показать описание
Syntax:
python
Copy code
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
# Shuffle the array in place
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)
python
Copy code
# Shuffle the rows in place
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
# Flatten the array, shuffle, then reshape back to the original 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)
python
Copy code
# Create a shuffled version of the array without modifying the original
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:
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!