This page demonstrates Python tips and tricks that I use in my everyday programming as an atmospheric science graduate student.
-Brian Blaylock

Friday, September 9, 2016

Sorting multiple vectors based on one vector sort order

That title was a mouthful. First, I want to sort an array vector. Then I want to sort other vectors with that same sort order.

I have a vector that contain heights, and with that two other vectors with the corresponding temperature and dew point. I want to sort the height array, and sort the temperature and dew point array in the same manner.

height = np.array([10, 50, 20, 30, 60, 20, 80])
temp = np.array([1, 4, 2, 7, 5, 3, 9])
dwpt = np.array([6, 3, 8, 5, 7, 4, 6])

First, use np.argsort to get the sort order.

sort_order = np.argsort(height)

[out] array([0, 2, 5, 3, 1, 4, 6], dtype=int64)

Now make new arrays of the sorted data with that sort order

sorted_height = np.array(height)[sort_order]
[out] array([10, 20, 20, 30, 50, 60, 80])

sorted_temp = np.array(temp)[sort_order]
[out] array([1, 2, 3, 7, 4, 5, 9])

sorted_dwpt = np.array(dwpt)[sort_order]
[out] array([6, 8, 4, 5, 3, 7, 6])

Thus, you see that we have sorted the height array from lowest to highest, and the temperature and dew point arrays have been sorted, preserving their order with the corresponding height.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.