Near as I can tell the numpy.sort function doesn’t support requesting a 
descending sort on specific columns.  (Docs: 
https://numpy.org/doc/stable/reference/generated/numpy.sort.html)  I wanted to 
check I’m not missing how this is properly done or if should I file this as a 
feature request.  There are many reasons one would need to choose sorting in 
ascending/descending order on a column by column basis. 

My first thought is another parameter to sort which is an array of bools to 
indicate sort order.  An alternative is to prepend ‘-‘ to column names that 
should be sorted in descending order. However the second idea may conflict with 
people's names for columns.

Thanks,
James Anderson

Example:

In my case I have an sweep line algorithm that needs to walk an ndarray with 
the following dtype row-by-row:
active_dtype = np.dtype([('Value', 'f4'), ('ID', 'u8'), ('Active', 'u1')])

I need to sort one column (Value) in ascending order, but another column 
(Active) in descending order. (To handle the degenerate case where a rectangle 
has a zero width/height).

For full context the code below takes a rectangle array (rect_array) and 
returns sorted arrays indicating where rectangle boundaries start and stop on 
each axis.  In this example one can invert the meaning of ‘Active’ to work 
around the lack of API support.  The intent is just to illustrate how I was 
hoping I had expected to use numpy.sort.

x_sweep_array = np.empty(len(rect_array) * 2, dtype=cls.active_dtype)
y_sweep_array = np.empty(len(rect_array) * 2, dtype=cls.active_dtype)
        
for i, rect in enumerate(rect_array):
  x_sweep_array[i * 2] = (rect['MinX'], rect['ID'], True)
  x_sweep_array[(i * 2) + 1] = (rect['MaxX'], rect['ID'], False)
  y_sweep_array[i * 2] = (rect['MinY'], rect['ID'], True)
  y_sweep_array[(i * 2) + 1] = (rect['MaxY'], rect['ID'], False)
            
x_sweep_array = np.sort(x_sweep_array, order=('Value', 'Active')) # <- Cannot 
reverse sort Active
y_sweep_array = np.sort(y_sweep_array, order=('Value', 'Active'))
        
return (x_sweep_array, y_sweep_array)
_______________________________________________
NumPy-Discussion mailing list -- numpy-discussion@python.org
To unsubscribe send an email to numpy-discussion-le...@python.org
https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
Member address: arch...@mail-archive.com

Reply via email to