numpy - 使用 numpy 中的查找值进行数组操作
问题描述
lookup = np.array([60, 40, 50, 70, 90])
a = np.array([1, 2, 1, 4, 3, 2, 4, 9, 1])
b = np.array([2, 1, 2, 3, 3, 4, 9, 2, 1])
c = np.array([4, 2, 1, 4, 4, 1, 4, 4, 9])
以下数组值对应于以下查找值:
1 --> 60
2 --> 40
3 --> 50
4 --> 70
9 --> 90
这是我必须做的
array 1st column elements lookup value
a 1 --> 60
b 2 --> 40
c 4 --> 70
最大值为 70。
因此,结果的第一个元素是 4。
这边走,
预期结果 = array([4, 1, ...., 9])
解决此类问题的更好方法是什么?
解决方案
您在这里有自定义索引,因此您需要设置一个字典来用查找值替换您的自定义索引,如下所示:
index_map = { 1: 60, 2: 40, 3: 50, 4: 70, 9: 90 }
lookup
然后,我们使用以下索引的实际值创建一个临时 NumPy 数组d
:
temp = np.array([index_map[int(x)] for x in np.nditer(d)]).reshape(d.shape)
因此,我们可以在您之前的问题(选项 1)中重新使用此有效答案:
rows = temp.argmax(0)
print(d[rows, np.arange(d.shape[1])])
输出:
[4 1 1 4 4 4 9 9 9]
推荐阅读
- javascript - jquery 正在调试,但在 IIS 上发布后无法正常工作
- python - Pandas Dataframe - 根据条件获取索引值
- php - 在 Laravel 5.6 中将用于格式化 DB 内容的代码放在哪里
- excel - Excel 异常行为:如果应用程序不可见,隐藏功能区也会隐藏标题栏
- java - 无法生成签名的 APK (java.lang.RuntimeException)
- apache-kafka - kafka-console-consumer 使用什么消费组
- javascript - 使用 JavaScript 创建 JSP 元素
- javascript - 如何在 Ext Js 6.5.2 的网格标题列菜单中对“列”进行排序
- powershell - 从变量中删除特定行
- typescript - 三个 JS - 将 2 个 CubicBezierCurve3 与平滑连接一起加入?