Reputation: 501
Hi I want to order a numpy.array using lexsort.
import numpy as np
surnames = ['Hertz', 'Galilei', 'Hertz']
names = ['Heinrich', 'Galilao', 'Gustav']
ind = np.lexsort((names,surnames))
But how can I have an array ordered according to this indexes?
I would do
surnames2 = surnames.copy()
for i, a in enumerate(ind):
surnames2[i] = surnames[a]
But I think there should be another way without writing the cycle by myself.
Thanks
Upvotes: 3
Views: 232
Reputation: 74242
If you turn surnames
into a numpy array then you can simply index it with the array of integers returned by lexsort
:
sorted_surnames = np.array(surnames)[ind]
If you want to stick with plain Python lists, you could do something like this:
sorted_surnames = [n for (i, n) in sorted(zip(ind, surnames), key=lambda x: x[0])]
Upvotes: 3