2

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 ?

3 Answers 3

4

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')
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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 w.r.t. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.