w3resource

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

NumPy: Array Object Exercise-176 with Solution

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:

import numpy as np
array_nums = np.arange(20).reshape(4,5)
print("Original array:")
print(array_nums)
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]]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to create an 1-D array of 20 elements. Now create a new array of shape (5, 4) from the said array, then restores the reshaped array into a 1-D array.
Next: Write a NumPy program to create an array of 4,5 shape and to reverse the rows of the said array. After reversing 1st row will be 4th and 4th will be 1st, 2nd row will be 3rd row and 3rd row will be 2nd row.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}