I have a list given filled with numpy arrays such as:
lst = [np.array([1, 2, 3, 4, 5]),
np.array([16, 17, 18, 19, 20]),
np.array([6, 7, 8, 9, 10]),
np.array([11, 12, 13, 14, 15])]
I have already tried sort and sorted functions, but I did not find the proper key to monitor serial numbers.
I would like to find out which place would the elements (numpy arrays) of the list take if I sorted them based on their sum.
Considering the example, my expected output would be:
output = [0, 3, 1, 2]
Thank you very much in advance.
CodePudding user response:
Use np.argsort
twice on the sum of elements:
import numpy as np
lst = [np.array([1, 2, 3, 4, 5]),
np.array([16, 17, 18, 19, 20]),
np.array([6, 7, 8, 9, 10]),
np.array([11, 12, 13, 14, 15])]
print(np.argsort(np.argsort(np.sum(lst, 1))))
Output:
[0 3 1 2]
CodePudding user response:
You can use scipy.stats.rankdata
:
import numpy as np
lst = [np.array([1, 2, 3, 4, 5]),
np.array([16, 17, 18, 19, 20]),
np.array([6, 7, 8, 9, 10]),
np.array([11, 12, 13, 14, 15])]
from scipy.stats import rankdata
out = (rankdata(np.sum(lst, 1))-1).astype(int)
# array([0, 3, 1, 2])
CodePudding user response:
I think expected output should be [0,2,3,1]
You can use sorted
import numpy as np
list_ = [np.array([1, 2, 3, 4, 5]), np.array([16, 17, 18, 19, 20]), np.array([6, 7, 8, 9, 10]), np.array([11, 12, 13, 14, 15])]
print([i for i, _ in sorted(zip(range(len(list_)), list_), key=lambda x: sum(x[1]))])