pandas - 如何获取 2-dim numpy 数组对的 topK 项?
问题描述
我有 2 个成对的 2-dim numpy 数组(比如标签和分数)
labels = np.array([['a','b','c','d'],
['a1','b1','c1','d1']])
scores = np.array([[0.1, 0.2, 0.3,0.4],
[1,2,3,4]])
我想从他们那里得到前 k 项,按分数第二行排序
我想我可以通过排序来实现:
[scores[i][1], scores[i][0], labels[i][0], labels[i][1]]
但是 numpy 或 pandas 库有没有更优雅的方法?
解决方案
numpy.argsort应该这样做
import numpy as np
labels = np.array([['a','b','c','d'],
['a1','b1','c1','d1']])
scores = np.array([[0.1, 0.2, 0.3,0.4],
[1,2,3,4]])
k = 2 # number of "top items"
idx = np.argsort(scores[-1])[-k:] # get the indices of top values
topkScores = scores[:,idx].T # you can remove .T if you wish to get the score pairs in columns
推荐阅读
- bash - gsutil cp 管道在 docker 容器中作为 bash exec 命令失败
- email - 如何使用 DataHandler 和 FileDataSource 在 apache camel 中发送带有附件和文件大小验证的邮件
- php - 获取 wordpress 帖子的更新值
- deep-learning - 如何解决这个问题“RuntimeError: CUDA out of memory.”?
- javascript - 谷歌账号可以实现二维码跨平台登录吗?
- sql - 在 sql teradata 中连接
- html - 自定义上传文件的输入
- ios - 如何将 UIImage 转换为 .JPEG 格式并将其发送到服务器?
- php - 有人能告诉我为什么这个简单的 PHP 循环不起作用吗?
- blob - 使用 JS 从 UUID 获取本地 BLOB