w3resource

NumPy: Rearrange columns of a given numpy 2D array using given index positions

NumPy: Array Object Exercise-159 with Solution

Write a NumPy program to rearrange columns of a given numpy 2D array using given index positions.

Sample Solution:

Python Code:

import numpy as np
array1 = np.array([[11, 22, 33, 44, 55],
             [66,  77,  88,  99, 100]])
print("Original arrays:")
print(array1)
i = [1,3,0,4,2]
result = array1[:,i]
print("New array:")
print(result)

Sample Output:

Original arrays:
[[ 11  22  33  44  55]
 [ 66  77  88  99 100]]
New array:
[[ 22  44  11  55  33]
 [ 77  99  66 100  88]]

Pictorial Presentation:

NumPy: Rearrange columns of a given numpy 2D array using given index positions

Python Code Editor:

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

Previous: Write a NumPy program to calculate average values of two given numpy arrays.
Next: Write a NumPy program to find the k smallest values of a given numpy array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

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