简体   繁体   中英

Vectorized sort of 2D numpy array columns independently

There must be a simple vectorized way to sort independently all columns in a 2D numpy array without 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM