2

I have the following array:

tasks = [["LNWBN","2017-08-13","2017-12-24","Corey","Kyle","Kaleb","Reuben"], 
["NSXEN","2017-08-20","2017-09-18","Kai"], 
["DNMDC","2017-06-19","2017-08-07","Kaleb","Kai","Kyle","Reuben"], 
["UYWEQ","2017-04-23","2017-07-18","Corey","Kyle","Reuben","Kai"], 
["LIVNH","2017-11-01","2017-12-24","Kaleb","Kai"]]

I would like to sort it by the third column followed by the first column so that the result is:

tasks = [["UYWEQ","2017-04-23","2017-07-18","Corey","Kyle","Reuben","Kai"], 
["DNMDC","2017-06-19","2017-08-07","Kaleb","Kai","Kyle","Reuben"], 
["NSXEN","2017-08-20","2017-09-18","Kai"], 
["LIVNH","2017-11-01","2017-12-24","Kaleb","Kai"],
["LNWBN","2017-08-13","2017-12-24","Corey","Kyle","Kaleb","Reuben"]]  

I tried using lexsort:

a = np.array(tasks)
ind = np.lexsort((a[:,2],a[:,0]))    
sorted_tasks = a[ind]

which is the top solution from here Sorting a 2D numpy array by multiple axes but I get the following error:

  ind = np.lexsort((a[:,2],a[:,0]))
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

I don't HAVE to use numpy, but that's the only way I found to sort 2D arrays by more than one axis

Appreciate any help.

1 Answer 1

1

Why don't you try python's sorted:

sorted(tasks, key=lambda x: (x[2],x[0]))

Output:

[['UYWEQ', '2017-04-23', '2017-07-18', 'Corey', 'Kyle', 'Reuben', 'Kai'],
 ['DNMDC', '2017-06-19', '2017-08-07', 'Kaleb', 'Kai', 'Kyle', 'Reuben'],
 ['NSXEN', '2017-08-20', '2017-09-18', 'Kai'],
 ['LIVNH', '2017-11-01', '2017-12-24', 'Kaleb', 'Kai'],
 ['LNWBN', '2017-08-13', '2017-12-24', 'Corey', 'Kyle', 'Kaleb', 'Reuben']]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.