How to reverse the columns of a 2D array with NumPy? Write a program to reverse the columns of a 2D array Sample data: [[0,1,2],[3,4,5],[6,7,8]] Sample output:[[210][5 4 3][8 76]]
时间: 2023-07-02 09:13:56 浏览: 105
Here's a code snippet that uses NumPy to reverse the columns of a 2D array:
```python
import numpy as np
# Define the 2D array
arr = np.array([[0,1,2],[3,4,5],[6,7,8]])
# Reverse the columns
arr_reversed = arr[:, ::-1]
# Print the original and reversed arrays
print("Original array:")
print(arr)
print("Reversed array:")
print(arr_reversed)
```
The `::` syntax is used to slice the array. The first `:` indicates that we want to select all rows, and the `::-1` indicates that we want to reverse the order of the columns.
And here is the output for the given sample data:
```
Original array:
[[0 1 2]
[3 4 5]
[6 7 8]]
Reversed array:
[[2 1 0]
[5 4 3]
[8 7 6]]
```
As you can see, the columns have been reversed in the output array.
阅读全文