How to Sort an Array by Column in Python?

Estimated read time 2 min read

To sort an array by column in Python, you can use the numpy.sort() function with the axis parameter set to the column index you want to sort by. This will sort the array by the values in the specified column.

Here’s an example implementation:

import numpy as np

# Define a 2D array
my_array = np.array([[4, 1, 9], [2, 3, 8], [8, 5, 7]])

# Sort the array by the values in the second column
sorted_array = my_array[np.argsort(my_array[:, 1])]

# Print the sorted array
print(sorted_array)

In this example, we define a 2D array my_array. We use the numpy.argsort() function to get the indices that would sort the array by the values in the second column. We then use these indices to sort the rows of the array based on the values in the second column, and assign the sorted array to the sorted_array variable. We then print the sorted array.

Note that numpy.argsort() returns the indices that would sort the array, so we use these indices to index the rows of the array to get the sorted array. The axis parameter of the numpy.sort() function specifies the axis along which to sort the array, so we do not use it directly here. Instead, we use the numpy.argsort() function to get the indices that would sort the array, and then use these indices to sort the rows of the array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply