Python Forum
What are these ordering code doing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What are these ordering code doing
#2
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]]
Reply


Messages In This Thread
What are these ordering code doing - by coltson - Nov-02-2020, 10:00 PM
RE: What are these ordering code doing - by deanhystad - Nov-03-2020, 05:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  drf ordering by custom field and add ranking in to_representation tomfong521 0 1,868 Mar-24-2021, 09:56 AM
Last Post: tomfong521
  Help with Matplotlib and ordering the axis theliberalguy97 3 8,057 Dec-12-2020, 08:06 PM
Last Post: deanhystad
  Ordering a list of dict giu88 2 2,742 Nov-05-2018, 02:12 PM
Last Post: giu88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020