python - 如何从带有索引的二维数组中获取值

标签 python numpy

例如,我有以下二维数组。

>>>np.array(((1,2),(3,4),(5,6))) 
>>>array([[1, 2],
          [3, 4],
          [5, 6]])

我想从每一列中获取一个元素。例如,我想从第一列获取 3,从第二列获取 6
如何用索引[1,2]来做到这一点。 1 表示第一列中的第二个元素,2 表示第二列中的第三个元素

最佳答案

您可以使用所谓的 fancy indexing 来做到这一点:

In [57]: x = np.array(((1,2),(3,4),(5,6)))

# np.arange(x.shape[1]) gives [0,1], the column indices
# needed to select "one from each column"
In [58]: x[[1,2], np.arange(x.shape[1])]
Out[58]: array([3, 6])
<小时/>

或者您可以使用np.choose :

In [44]: np.choose([1,2], x)
Out[44]: array([3, 6])

关于python - 如何从带有索引的二维数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676374/

相关文章:

python - 如何减少python列表算法中k个连续数字的最大和的执行时间

python - 在有条件的循环中列出索引超出范围

python - 如何使用 LSB 替换将一张图像隐藏到另一张图像中?

numpy - 使用 Conv2d 进行图像调整

python - 将 numpy.in1d() 与数组及其单个元素一起使用的不同结果

python - 如何从 Python 脚本中列出 Python 可用的所有包/模块?

python - shutil.move(scr, dst) 得到 IOError : [Errno 13] Permission denied and 3 more errors

python - 通过模式匹配相乘

python - 在 python 中使用 HTML 表单输入数据时,MySQL 数据不显示

python - 比较同一数据框列中的值