简体   繁体   English

每列的numpy索引

[英]numpy indexing for each column

I want to get items from an array by indexing for each column. 我想通过为每一列建立索引来从数组中获取项目。 For example, an index like: 例如,索引如下:

[[1, 3],
 [2, 4]]

Would mean: 表示:

  1. get the 1st and 2nd element of the zeroth column of the array, and put them in the zeroth column of the result. 获取数组第0列的第1个和第2个元素,并将它们放在结果的第0列中。

  2. get the 3rd and 4th element of the 1st column of the array, and put them in the 1st column of the result. 获取数组第一列的第三和第四元素,并将它们放在结果的第一列中。

Program: 程序:

import numpy as np
arr = np.arange(12).reshape(3,4)
print(arr)

ind = np.array(
    [[1,1,1,1],
     [2,2,2,2]]
)

result = arr[np.arange(2)[:, np.newaxis], ind[np.newaxis,:]]
print(result)

Result: 结果:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

[[[1 1 1 1]
  [6 6 6 6]]]

Expected result: 预期结果:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

[[[4 5 6 7]
  [8 9 10 11]]]

How to get the expected result? 如何获得预期的结果?

This works: 这有效:

import numpy as np
x = np.arange(12).reshape(3,4)

y = np.array(
    [[1,1,1,1],
     [2,2,2,2]]
)

z = x[y[:, np.newaxis], np.arange(4)[np.newaxis, :]]

print(z)

Result: 结果:

[[[ 4  5  6  7]]

 [[ 8  9 10 11]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM