Nov-03-2020, 05:07 AM
order = mothFit.argsort()
creates an array or matrix the same size as mothFit which contains indices that will result in a sorted list. Since there is no "axis" argument specified, mothFit is sorted along the "last" axis. Axis 0 sorts the values in colomns (along the rows axis), Axis 1 sorts values in rows (along the columns axis). The "last" axis is Axis 1.This is a complete, though short example.
import numpy as np x = np.array([[1,6,3],[2,5,4]]) i = x.argsort() y = np.take_along_axis(x, i, axis=1) print('Sort each row\nIndices\n', i) print('Sorted Values\n', y)
Output:Sort each row
Indices
[[0 2 1] # In first row, the middle number is moved to the end
[0 2 1]] # Same for the second row
Sorted Values
[[1 3 6] # Values in a row are sorted in increasing value
[2 4 5]]
You can specify the sorting axis = 0 and sort the values in a column.i = x.argsort(axis=0) y = np.take_along_axis(x, i, axis=0) print('\nSort each column\nIndices\n', i) print('Sorted Values\n', y)
Output:Sort each column
Indices
[[0 1 0] # Need to flip middle column
[1 0 1]]
Sorted Values
[[1 5 3] # All columns sorted in increasing order
[2 6 4]]
If you set axis = None, the matrix is sorted as a flat list.i = x.argsort(axis=None) y = np.take_along_axis(x, i, axis=None) print('\nFlat sort\nIndices\n', i) print('Sorted Values\n', y)
Output:Flat sort
Indices
[0 3 2 5 4 1]
Sorted Values
[1 2 3 4 5 6]
Sorting the values to to still be in matrix form requires the additional step of splitting the array into two parts.i = x.argsort(axis=None) y = np.take_along_axis(x, i, axis=None) z = np.array(np.array_split(y, 2)) print('\nFlat sort\nIndices\n', i) print('Sorted Values\n', z)
Output:Flat sort
Indices
[0 3 2 5 4 1]
Sorted Values
[[1 2 3]
[4 5 6]]