python - numpy 中的索引(与 max/argmax 相关)

标签 python arrays numpy

假设我有一个 N 维 numpy 数组 x 和一个 (N-1) 维索引数组 m(例如,m = x。 argmax(轴=-1))。我想构造 (N-1) 维数组 y 使得 y[i_1, ..., i_N-1] = x[i_1, ..., i_N-1 , m[i_1, ..., i_N-1]](对于上面的 argmax 示例,它等同于 y = x.max(axis=-1) )。 对于 N=3 我可以通过

实现我想要的
y = x[np.arange(x.shape[0])[:, np.newaxis], np.arange(x.shape[1]), m]

问题是,我如何对任意 N 执行此操作?

最佳答案

你可以使用indices :

firstdims=np.indices(x.shape[:-1])

然后添加你的:

ind=tuple(firstdims)+(m,) 

那么 x[ind] 就是你想要的。

In [228]: allclose(x.max(-1),x[ind]) 
Out[228]: True

关于python - numpy 中的索引(与 max/argmax 相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315762/

相关文章:

使用 nosetests.exe 的 Python 单元测试阻止使用日志记录模块登录文件

python - 如何使 random.choices 真正随机(我在 secrets 模块中找不到它)

php - 将数组的所有索引放在逗号分隔的字符串中

python - 如何设置元素数量等于另一列列表中元素数量的列列表

Python ctypes 到位域的 np.dtype 转换

python - 类方法的同一性

jquery - python的Web框架推荐(webservices, auth, cache, ...)

javascript - 使用键将对象放入数组然后显示它们

mysql - 将 mysql2 类型转换为数组并在 ruby​​ 中对其进行排序

python - scipy.integrate.ode.integrate() 可选的 `step` 和 `relax` 参数有什么作用?