w3resource

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


Rearrange columns of a 2D array using indices.

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

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array
array1 = np.array([[11, 22, 33, 44, 55],
                    [66, 77, 88, 99, 100]])

# Displaying the original array
print("Original arrays:")
print(array1)

# Creating a list of indices for reordering columns
i = [1, 3, 0, 4, 2]

# Rearranging the columns of the original array based on the given indices
result = array1[:, i]

# Displaying the new array formed by rearranging columns
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]]

Explanation:

In the above exercise -

  • array1 = np.array([[11, 22, 33, 44, 55], [66, 77, 88, 99, 100]]): Create a 2D NumPy array with given values.
  • i: Define a list of column indices representing the desired order of columns.
  • array1[:,i]: Rearrange the columns of array1 according to the specified order in i. Here, the colon : means to select all rows and ‘i’ is the list of column indices in the desired order.
  • result: Store the resulting NumPy array.

Pictorial Presentation:

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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to rearrange the columns of a 2D array according to a given permutation of indices using advanced indexing.
  • Create a function that accepts a 2D array and a list of column indices, then returns the array with rearranged columns.
  • Implement a solution that uses np.take along axis 1 to reorder the columns based on a provided index array.
  • Test the column rearrangement on matrices with duplicate and unsorted indices to verify correct ordering.

Go to:


PREV : Calculate average values of two arrays.
NEXT : Find k smallest values in an array.


Python-Numpy Code Editor:

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

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.