python - 给定索引数组(i1,i2,...),获取 numpy 嵌套数组中的第 i 个元素
问题描述
给定x
一个 numpy 数组:
>>> x
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
还有另一个数组/索引列表:
>>> indices = [2, 1, 1]
是否有一个将两者都作为输入的 numpy 方法:
>>> np.some_method(x, indices, axis=1)
并返回:
array([ 3, 6, 10]) # for the given indices (2, 1, 1) respectively
解决方案
正如评论中提到的@Dani,您可以使用高级索引:
x[np.arange(3), indices]
推荐阅读
- machine-learning - 如何改进 Levenberg-Marquardt 的多项式曲线拟合方法?
- python - 如何在 python 中创建函数以使它们将 x 作为变量返回?(插值)
- java - 无法在 docker 中构建 gradle 应用程序
- python - pandas.io.sql.DatabaseError:在 sql 上执行失败
- javascript - 如何将两个数组作为键和值合并到一个具有多个值的键的对象中?
- python - Plotly hover_data 不适用于 dict?
- razor - 如何在 Razor Dotnet 核心项目的子文件夹中运行 Blazor 应用程序项目?
- api - 如何使用推送通知和 API 制作反应原生应用程序
- r - 如何在 R 中编写一个函数来复制多个列,每次添加不同的后缀?
- java - 在同一按钮上使用动作侦听器时出现摆动错误