Reputation: 4083
I have two lists in python3.6, and I would like to sort w
by considering d
values. This is similar to this question,
Sorting list based on values from another list? , though, I could not use zip
because w
and d
are not paired data.
I have a code sample, and want to get t
variable.
I could do it by using for loop. Is there any fasterh way?
import numpy as np
w = np.arange(0.0, 1.0, 0.1)
t = np.zeros(10)
d = np.array([3.1, 0.2, 5.3, 2.2, 4.9, 6.1, 7.7, 8.1, 1.3, 9.4])
ind = np.argsort(d)
print('w', w)
print('d', d)
for i in range(10):
t[ind[i]] = w[i]
print('t', t)
#w [ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
#d [ 3.1 0.2 5.3 2.2 4.9 6.1 7.7 8.1 1.3 9.4]
#ht [ 0.3 0. 0.5 0.2 0.4 0.6 0.7 0.8 0.1 0.9]
Upvotes: 1
Views: 258
Reputation: 1639
The answers for this question are fantastic, but I feel it is prudent to point out you are not doing what you think you are doing.
What you want to do: (or at least what I gather) You want t
to contain the values of w
rearranged to be in the sorted order of d
What you are doing: Filling out t
in the sorted order of d
, with elements of w
. You are only changing the order of how t
gets filled up. You are not reflecting the sort of d
into w
on t
Consider a small variation in your for
loop
for i in range(0,10):
t[i] = w[ind[i]]
This outputs a t
('t', array([0.1, 0.8, 0.3, 0. , 0.4, 0.2, 0.5, 0.6, 0.7, 0.9]))
You can just adapt PaulPanzer's answer to this as well.
Upvotes: 1
Reputation: 53029
Use argsort
like so:
>>> t = np.empty_like(w)
>>> t[d.argsort()] = w
>>> t
array([0.3, 0. , 0.5, 0.2, 0.4, 0.6, 0.7, 0.8, 0.1, 0.9])
Upvotes: 3
Reputation: 77837
They are paired data, but in the opposite direction.
i
, np.arange(0, 10). zip
this with d
.d
as the sort key; i
still holds the original index of each d
element.zip
this with w
.i
as the sort key.w
values in their new order; this is your t
array.Upvotes: 1