1

I have a 2D numpy array and I want to change this array into a 1D which is sorted. For example:

A = [[1,0,2],
     [0,3,0]]

I want this to be like:

B = [3,2,1,0,0,0]

Any idea how I can do this using python modules and not to write a sorting algorithm or anything like that ?

Thanks

2 Answers 2

4

Assuming you are looking to sort them in descending order -

In [127]: A
Out[127]: [[1, 0, 2], [0, 3, 0]]

In [128]: B = np.sort(np.array(A).ravel())

In [129]: B[::-1]
Out[129]: array([3, 2, 1, 0, 0, 0])

Basically, it involves three steps: Flatten the array with ravel(), sort it with np.sort and then reverse the indexing for an effect of descending order sorting.

Sign up to request clarification or add additional context in comments.

2 Comments

@EdChum haha happens I guess! :)
@EdChum Ah that was okay! Well, I liked your one-liner though.
1

This is my solution:

A = [[1,0,2], [0,3,0]]
B = []
for i in range(len(A)):
    for j in range(len(A[i])):
        B.append(A[i][j])

B.sort(cmp=None, key=None, reverse=True)
print B

You can see my code running here: http://ideone.com/P8xBPK

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.