Numpy - Reversing Rows and Columns

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 7:- Numpy - Reversing Rows and Columns

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:

  1. 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 code
    import 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]]
  2. 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 code
    import 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]]
  3. 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 code
    import 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.

 

Disclaimer: 

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.

2. Handling Data

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support