1

I want to turn a 1d array into a sorted 2d array. The 1d array looks like this:

[1,5,8,9,9,1,4,6,7,8,41,4,5,31,6,11]

First, I want to split this array up into a 2d array with a width of 4.

    [[1,5,8,9]
     [9,1,4,6]
     [7,8,41,4]
     [5,31,6,11]
    ]

Then, I want to sort the 2d array from the 3rd value in the 2d array like this:

    [[9,1,4,6],
     [5,31,6,11],
     [1,5,8,9],
     [7,8,41,4]
    ]

I am anticipating that the 1d array will be much larger, so I do not want to manually create the 2d array. How do I approach this?

3 Answers 3

1

If you can't use numpy, you can do it like this:

a = [1,5,8,9,9,1,4,6,7,8,41,4,5,31,6,11]
result = []
l = len(a)
for i in range(0, l, 4):
    result.append(a[i:i+4])

result = sorted(result, key = lambda a: a[2])
# result is [[9, 1, 4, 6], [5, 31, 6, 11], [1, 5, 8, 9], [7, 8, 41, 4]]
Sign up to request clarification or add additional context in comments.

Comments

0

You can try numpy array_split

import numpy as np
a=[1,5,8,9,9,1,4,6,7,8,41,4,5,31,6,11]
b=np.array_split(arr, len(a)/4)
for c in b:
   c.sort()

1 Comment

Even after correcting the typo (arr/a), this doesn't provide the expected output.
0

If you use numpy.argsort, you can sort it easily.

import numpy as np
arr = np.array([1,5,8,9,9,1,4,6,7,8,41,4,5,31,6,11])
arr_2d = np.reshape(arr, (4,4))
sorted_arr = arr_2d[np.argsort(arr_2d[:, 2])]

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.