Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer
    
balls beaten by 18 secs +1 – EdChum Apr 17 '15 at 22:12
    
@EdChum haha happens I guess! :) – Divakar Apr 17 '15 at 22:13
    
Sorry I ran out of votes today :( so I couldn't upvote, will remember in a few hours, going to delete my answer now – EdChum Apr 17 '15 at 22:14
    
@EdChum Ah that was okay! Well, I liked your one-liner though. – Divakar Apr 17 '15 at 22:15

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.