3

(Python 2.7.12) - I have created an NxN array, when I print it I get the exact following output:

Sample a:

SampleArray=np.random.randint(1,100, size=(5,5))    
    [[49 72 88 56 41]
     [30 73  6 43 53]
     [83 54 65 16 34]
     [25 17 73 10 46]
     [75 77 82 12 91]]
  • Nice and clean.

However, when I go to sort this array by the elements in the 4th column using the code:

SampleArray=sorted(SampleArray, key=lambda x: x[4])

I get the following output:

Sample b:

[array([90,  9, 77, 63, 48]), array([43, 97, 47, 74, 53]), array([60, 64, 97,  2, 73]), array([34, 20, 42, 80, 76]), array([86, 61, 95, 21, 82])]

How can I get my output to stay in the format of 'Sample a'. It will make debugging much easier if I can see the numbers in a straight column.

1
  • The display changes because it's a different type of object. One was an array, the other is a list. In Python each type of object has its own display format. Commented Sep 27, 2017 at 16:02

3 Answers 3

3

Simply with numpy.argsort() routine:

import numpy as np

a = np.random.randint(1,100, size=(5,5))
print(a)   # initial array
print(a[np.argsort(a[:, -1])])  # sorted array

The output for # initial array:

[[21 99 34 33 55]
 [14 81 92 44 97]
 [68 53 35 46 22]
 [64 33 52 40 75]
 [65 35 35 78 43]]

The output for # sorted array:

[[68 53 35 46 22]
 [65 35 35 78 43]
 [21 99 34 33 55]
 [64 33 52 40 75]
 [14 81 92 44 97]]
Sign up to request clarification or add additional context in comments.

Comments

0

you just need to convert sample array back to a numpy array by using

SampleArray = np.array(SampleArray)

sample code:-

import numpy as np
SampleArray=np.random.randint(1,100, size=(5,5))    

print (SampleArray)
SampleArray=sorted(SampleArray, key=lambda x: x[4])
print (SampleArray)
SampleArray = np.array(SampleArray)
print (SampleArray)

output:-

[[28 25 33 56 54]
 [77 88 10 68 61]
 [30 83 77 87 82]
 [83 93 70  1  2]
 [27 70 76 28 80]]
[array([83, 93, 70,  1,  2]), array([28, 25, 33, 56, 54]), array([77, 88, 10, 68, 61]), array([27, 70, 76, 28, 80]), array([30, 83, 77, 87, 82])]
[[83 93 70  1  2]
 [28 25 33 56 54]
 [77 88 10 68 61]
 [27 70 76 28 80]
 [30 83 77 87 82]]

Comments

-1

This can help:

from pprint import pprint
pprint(SampleArray)

The output is a little bit different from the one for Sample A but it still looks neat and debugging will be easier.

Edit: here's my output

[[92  8 41 64 61]
 [18 67 91 80 35]
 [68 37  4  6 43]
 [26 81 57 26 52]
 [ 6 82 95 15 69]]

[array([18, 67, 91, 80, 35]),
 array([68, 37,  4,  6, 43]),
 array([26, 81, 57, 26, 52]),
 array([92,  8, 41, 64, 61]),
 array([ 6, 82, 95, 15, 69])]

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.