Numpy - how to sort an array of value/key pairs in descending order

2024/10/10 18:24:17

I was looking at the problem Fastest way to rank items with multiple values and weightings and came up with the following solution, but with two remaining issues:

import numpy as np# set up values
keys = np.array([['key1'],['key2'],['key3']
])
values = np.matrix([[1.1, 1.2, 1.3, 1.4],[2.1, 2.2, 2.3, 2.4],[3.1, 3.2, 3.3, 3.4]
])
weights = np.matrix([10., 20., 30., 40.]).transpose()# crunch the numbers
res = values * weights# combine results with labels
items = np.hstack((np.array(res), keys))# !First problem - .hstack has promoted the first column from float64 to S4:
# array([['130.', 'key1'],
#        ['230.', 'key2'],
#        ['330.', 'key3']], 
#       dtype='|S4')
# How can I force it to stay numeric?items.sort(reverse=True)   # doesn't work, no 'reverse' argument# !Second problem - how to sort the array in descending order?
Answer

You could merge res and keys into a structured array:

import numpy.lib.recfunctions as recfunctions
items = recfunctions.merge_arrays([res,keys])

Since np.sort does not have a reverse=True flag, I think the best you can do is reverse the returned array, (e.g. items[::-1]) or else take the negative of res:

import numpy as np
import numpy.lib.recfunctions as recfunctions# set up values
keys = np.array([['key1'],['key2'],['key3']
])
values = np.matrix([[1.1, 1.2, 1.3, 1.4],[2.1, 2.2, 2.3, 2.4],[3.1, 3.2, 3.3, 3.4]
])
weights = np.matrix([10., 20., 30., 40.]).transpose()# crunch the numbers
res = values * weights# combine results with labels
res = np.asarray(-res)
items = recfunctions.merge_arrays([res,keys])
items.dtype.names = ['res', 'key']
items.sort(order=['res'])
print(items)

yields

[(-330.0, 'key3') (-230.0, 'key2') (-130.0, 'key1')]

Note that refunctions.merge_arrays is just a Python convenience function. It uses zip and np.fromiter. It would definitely be faster to avoid joining res and keys and instead use argsort to find the indices that sort res and use those to reorder keys:

import numpy as np# set up values
keys = np.array([['key1'],['key2'],['key3']
])
values = np.matrix([[1.1, 1.2, 1.3, 1.4],[2.1, 2.2, 2.3, 2.4],[3.1, 3.2, 3.3, 3.4]
])
weights = np.matrix([10., 20., 30., 40.]).transpose()# crunch the numbers
res = values * weights# combine results with labels
res = np.squeeze(np.asarray(res))
idx = np.argsort(res)[::-1]
print(keys[idx])
print(res[idx])

yields

[['key3']['key2']['key1']]
[ 330.  230.  130.]
https://en.xdnf.cn/q/118420.html

Related Q&A

How to extract certain under specific condition in pandas? (Sentimental analysis)

The picture is what my dataframe looks like. I have user_name, movie_name and time column. I want to extract only rows that are first day of certain movie. For example, if movie as first date in the ti…

Flask app.run method does not work with WinPython 3.11.1 and next.js application: fetch failed

When using WinPython 3.10.5 I am able to debug my flask & next.js application using the flask debug mode (to enable hot reloads): app.run(debug=True, host=host, port=port)However, when using WinPyt…

Pythonic way to assign global administrator roles for Azure Active Directory

What specifically needs to be changed in the Python 3 code below in order to successfully assign the Global Administrator role for an Azure Active Directory Tenant to a given service principal? We tri…

Pandas calculating age from a date

I really need help with this one. My previous post was very bad and unclear - Im sorry - I wish I could delete but hopefully this one will be better.I need to calculate the age based off of a date (se…

Create new folders within multiple existing folders with python

I am looking for a way to create new folders within multiple existing folders. For example I have folders a,b,c.. etc and I want to create a new folder inside each of these existing folders and name th…

extract a column from text file

I have a a text file (huge amount of float numbers) with 25 columns. I want to extract column 14 and divide it by column 15. I could not extract this two columns. Codes:with open(sample for north.txt) …

kivy buildozer Compile Error pythonforandroid.toolchain

Compile platformCommand failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=main -- bootstrap=sdl2 --requirements=kivy,python3 --arch armeabi- v7a --copy-libs --color=always --…

Django Error: No FlatPage matches the given query

SITE_ID = 1and (r, include(django.contrib.flatpages.urls)), is in urls.py.What can I do to fix this error? Django is still displaying this error - I have googled and I cant find anything.File urls.pyf…

I need to automate the filling of a HTML form in a web browser, how?

I am trying to build a python script that captures my screen (a website will be opened), finds the coordinates of a text entry box on the displayed web site, and then clicks in that text entry box. I a…

Page not found (404) at /user_signup in Django

Getting 404 error on signup and some more URLs. /login, /logout, /admin is working perfectly. Im making a web app that lets a user login, logout, search a flight, book a flight and view the bookings ma…