简体   繁体   中英

sorting a python multi-dimensional array?

I declared a multidimensional array that can accept different data types using numpy

count_array = numpy.empty((len(list), 2), dtype = numpy.object)

The first array has got strings and the second has got numbers. I want to sort both the columns on the basis of the numbers ...

Is there any easier way like sort() method to do this ?

Consider making your array a structured array instead:

count_array = np.empty((len(list),), dtype=[('str', 'S10'), ('num', int)])

Then you can just sort by a specific key:

np.sort(arr, order='num')

You could argsort the second column, then use so-called "fancy-indexing" on the rows:

import numpy as np
count_array = np.array([('foo',2),('bar',5),('baz',0)], dtype = np.object)
print(count_array)
# [[foo 2]
#  [bar 5]
#  [baz 0]]

idx = np.argsort(count_array[:, 1])
print(idx)
# [2 0 1]

print(count_array[idx])
# [[baz 0]
#  [foo 2]
#  [bar 5]]

I propose this one:

First, like unutbu, I would use numpy.array to build list

import numpy as np
count_array = np.array([('foo',2),('bar',5),('baz',0)], dtype = np.object)

Then, I sort using operator.itemgetter :

import operator
newlist = sorted(count_array, key=operator.itemgetter(1))

which means: sort count_array wrt argument with index 1, that is the integer value.

Output is

[array([baz, 0], dtype=object), array([foo, 2], dtype=object), array([bar, 5], dtype=object)]

that I can rearrange. I do this with

np.array([list(k) for k in newlist], dtype=np.object)

and I get a numpy array with same format as before

array([[baz, 0],
       [foo, 2],
       [bar, 5]], dtype=object)

In the end, whole code looks like that

import numpy as np
import operator

count_array = np.array([('foo',2),('bar',5),('baz',0)], dtype = np.object)

np.array([list(k) for k in sorted(count_array, key=operator.itemgetter(1))], dtype=np.object)

with last line doing the requested sort.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM