2

How to sort the following matrix:

import numpy as np

A = np.array([['2', '2', '2', 'd'],
              ['1', '1', '3', 'c'],
              ['1', '13', '1', 'a'],
              ['1', '11', '3', 'b']], dtype='<U2')

based on the numbers in the text cells and based on multiple columns? With lists sorting works as follows:

sorted([[2, 2, 2, 'd'],
        [1, 1, 3, 'c'],
        [1, 13, 1, 'a'],
        [1, 11, 3, 'b']], key = lambda k: (k[0],k[2],-k[1]))

Out[1]: [[1, 13, 1, 'a'], [1, 11, 3, 'b'], [1, 1, 3, 'c'], [2, 2, 2, 'd']]

but how could I sort the numpy array A similar to the list above?

First trial was not successful ...

sorted(A, key = lambda k: (k[0],k[2],-k[1]))

Traceback (most recent call last):

File "< ipython-input-... >", line 1, in sorted(A, key = lambda k: (k[0],k[2],-k[1]))

TypeError: bad operand type for unary -: 'numpy.str_'

2 Answers 2

2

The error says you can't negate numpy.str_ object sounds logical. But for solving your problem, I suggest you first sort the array with reverse ordering and key k[1] and then sort this result with two other keys.

t = sorted(A, key = lambda k: k[1], reverse=True)
t = sorted(t, key = lambda k: (k[0],k[2]))
Sign up to request clarification or add additional context in comments.

2 Comments

In this solution one would also need type conversion to int(k[...]), as @yatu suggested. The problem was to sort numerically the strings, because alphabetical order does not quarantee numerical order.
Yes, but I thought you need alphabetical order and maybe you have other than numbers in your strings.
1

You have to convert the sliced values to int:

sorted(A, key = lambda k: (int(k[0]),int(k[2]),-int(k[1])))

[array(['1', '13', '1', 'a'], dtype='<U2'),
 array(['1', '11', '3', 'b'], dtype='<U2'),
 array(['1', '1', '3', 'c'], dtype='<U2'),
 array(['2', '2', '2', 'd'], dtype='<U2')]

1 Comment

It can't compare strings!! maybe we cant convert that string to integers.

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.