If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In NumPy, you can reverse the rows and columns of an array using simple slicing operations. Here's how you can reverse the rows and columns of a NumPy array:
Reverse Rows: To reverse the rows of an array, you can use slicing with a step of -1 along the first axis (axis=0). This will reverse the order of rows in the array.
pythonCopy codeimport numpy as np
# Original 2D array
original_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Reversed rows
reversed_rows_array = original_array[::-1, :]
# Output
print(reversed_rows_array)
Output:
luaCopy code[[7 8 9]
[4 5 6]
[1 2 3]]
Reverse Columns: To reverse the columns of an array, you can use slicing with a step of -1 along the second axis (axis=1). This will reverse the order of columns in the array.
pythonCopy codeimport numpy as np
# Original 2D array
original_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Reversed columns
reversed_columns_array = original_array[:, ::-1]
# Output
print(reversed_columns_array)
Output:
luaCopy code[[3 2 1]
[6 5 4]
[9 8 7]]
Reverse Rows and Columns: To reverse both the rows and columns simultaneously, you can use both row and column slicing with a step of -1.
pythonCopy codeimport numpy as np
# Original 2D array
original_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Reversed rows and columns
reversed_rows_columns_array = original_array[::-1, ::-1]
# Output
print(reversed_rows_columns_array)
Output:
luaCopy code[[9 8 7]
[6 5 4]
[3 2 1]]
In all of the above examples, the [::-1]
slicing reverses the order along the specified axis (rows in the case of reverse rows and columns in the case of reverse columns). Keep in mind that these operations create a new array; the original array remains unchanged. If you want to modify the original array in place, you can use the np.flip
function with appropriate axis arguments.
Copyright Disclaimer under Section 107 of the copyright act 1976, allowance is made for fair use fo purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational or personal use tips the balance in favor of fair use.
Comments: 0