Vectorized sort of 2D numpy array columns independently

Viewed 86

There must be a simple vectorized way to sort independently all columns in a 2D numpy array without using a for cycle.

input_arr = np.array([[6,4],[3,1],[2,5]])

out_arr =np.empty_like(input_arr)
for c,column in enumerate(input_arr.T):
    out_arr[:,c] = np.sort(column)
Expected results:
unsorted:
[[6 4]
 [3 1]
 [2 5]]

columns_sorted:
[[2 1]
 [3 4]
 [6 5]]

Can you help me out?

1 Answers
np.sort(np.array([[6,4],[3,1],[2,5]]).T).T

EDIT:

Better and simpler solution, thanks to @user3483203

np.sort(np.sort(np.array([[6,4],[3,1],[2,5]]), axis=0)
Related