How to get a numpy array from multiple lists of the same length and sort along the axis?

I have a very simple question: how to get a numpy array from multiple lists of the same length and sort along the axis?

I'm looking for something like:

a = [1,1,2,3,4,5,6]
b = [10,10,11,09,22,20,20]
c = [100,100,111,090,220,200,200]
d = np.asarray(a,b,c)
print d
>>>[[1,10,100],[1,10,100],[2,11,111].........[6,20,200]]

      

2nd question: And if this can be achieved, can I sort it along the axis (e.g. for List b values)?

3rd question: Can sorting be done on a range? eg. for values ​​between b + 10 and b-10 when traversing list c for further sorting. as

[[1,11,111][1,10,122][1,09,126][1,11,154][1,11,191]
 [1,20,110][1,25,122][1,21,154][1,21,155][1,21,184]]

      

+3


source to share


2 answers


You can zip the array:

a = [1, 1, 2, 3, 4, 5, 6]
b = [10, 10, 11, 9, 22, 20, 20]
c = [100, 100, 111, 90, 220, 200, 200]
d = np.asarray(zip(a,b,c))
print(d)
[[  1  10 100]
 [  1  10 100]
 [  2  11 111]
 [  3   9  90]
 [  4  22 220]
 [  5  20 200]
 [  6  20 200]]

print(d[np.argsort(d[:, 1])]) # a sorted copy
[[  3   9  90]
[  1  10 100]
[  1  10 100]
[  2  11 111]
[  5  20 200]
[  6  20 200]
[  4  22 220]]

      

I don't know how you would do the inplace sort without doing something like:

d = np.asarray(zip(a,b,c))

d.dtype = [("0", int), ("1", int), ("2", int)]
d.shape = d.size
d.sort(order="1")

      



The presenter 0

will do octal 090

in python2 or invalid syntax in python3 so that I remove it.

You can also sort the zipped items before passing:

from operator import itemgetter
zipped = sorted(zip(a,b,c),key=itemgetter(1))


d = np.asarray(zipped)
print(d)
[[  3   9  90]
 [  1  10 100]
 [  1  10 100]
 [  2  11 111]
 [  5  20 200]
 [  6  20 200]
 [  4  22 220]]

      

+2


source


You can use np.dstack

and np.lexsort

. for example if you want to sort based on an array b

(second axis) then then a

and then c

:



>>> d=np.dstack((a,b,c))[0]
>>> indices=np.lexsort((d[:,1],d[:,0],d[:,2]))
>>> d[indices]
array([[  3,   9,  90],
       [  1,  10, 100],
       [  1,  10, 100],
       [  2,  11, 111],
       [  5,  20, 200],
       [  6,  20, 200],
       [  4,  22, 220]])

      

+1


source







All Articles