Reputation: 35
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?
Upvotes: 1
Views: 298
Reputation: 11
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])]
Upvotes: 0
Reputation: 5738
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]]
Upvotes: 1
Reputation: 61
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()
Upvotes: 0