python - 基于 2D numpy 索引数组排列 numpy 2D 数组的 numpy 方式是什么?

标签 python arrays numpy

import numpy as np
x = np.array([[1,2 ,3], [9,8,7]])
y = np.array([[2,1 ,0], [1,0,2]])

x[y]

预期输出:

array([[3,2,1], [8,9,7]])

如果 x 和 y 是一维数组,则 x[y] 可以。那么对二维数组执行此操作的 numpy 方式或最 pythonic 或有效的方式是什么?

最佳答案

您需要定义相应的行索引。

一种方法是:

>>> x[np.arange(x.shape[0])[..., None], y]
array([[3, 2, 1],
       [8, 9, 7]])

关于python - 基于 2D numpy 索引数组排列 numpy 2D 数组的 numpy 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274838/

相关文章:

python - python 请求库中的 https 代理支持

python - ValueError 验证循环

python - 根据元组的总和获取元组元素的乘积

ios - 如何从 Firebase 检索数据到 UITableViewCell

python - scikit-learn 中的 "ValueError: could not convert string to float"错误

python - Keras/Tensorflow 中基于切片的分配?

python - 如何在 python 中创建概率条件流?

php - 使用 array_push() 帮助

php - 将 PHP 中的嵌套(多维)数组更改为 key => value 对

python - 在 Ubuntu 上使用 pip 安装 NumPy 失败