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
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])]
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.