w3resource

NumPy: Create an array of 4,5 shape and swap column1 with column4


Swap specific columns in a 2D array.

Write a NumPy program to create an array of 4,5 shape and swap column1 with column4.

Pictorial Presentation:

Python NumPy: Create an array of 4,5 shape and swap column1 with column4

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Creating a NumPy array using arange from 0 to 19 and reshaping it to a 4x5 array
array_nums = np.arange(20).reshape(4, 5)

# Printing the original array
print("Original array:")
print(array_nums)

# Swapping column 1 with column 4 in the array
print("\nAfter swapping column1 with column4:")
array_nums[:, [0, 3]] = array_nums[:, [3, 0]]
print(array_nums) 

Sample Output:

Original array:
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]

After swapping column1 with column4:
[[ 3  1  2  0  4]
 [ 8  6  7  5  9]
 [13 11 12 10 14]
 [18 16 17 15 19]]

Explanation:

In the above code -

array_nums = np.arange(20).reshape(4,5): This line creates a 1-dimensional NumPy array containing numbers from 0 to 19 and then reshapes it into a 2-dimensional array with 4 rows and 5 columns.

array_nums[:,[0,3]] = array_nums[:,[3,0]]: This line swaps the first (0-th) and fourth (3-rd) columns within the array. The syntax array_nums[:,[0,3]] selects all rows of the first and fourth columns, while array_nums[:,[3,0]] selects all rows of the fourth and first columns, respectively. By setting array_nums[:,[0,3]] equal to array_nums[:,[3,0]], we effectively swap the positions of the first and fourth columns.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to swap two specified columns in a 2D array using advanced indexing.
  • Create a function that accepts a 2D array and two column indices, then returns a new array with those columns swapped.
  • Implement a solution that uses np.copy to perform an in-place swap without altering the original array.
  • Test the column swap on arrays with both even and odd numbers of columns to verify consistent behavior.

Go to:


PREV : Reshape 1D array to 2D and restore.
NEXT : Reverse the rows of a 2D array.


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.