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:

# 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

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.