带列表的 Numpy 切片

时间:2021-06-11 16:13:18

标签: numpy numpy-slicing

我正在尝试使用列表 a 对 Ndarray b 进行切片。但行为并不像我所期望的那样。我需要改变什么才能得到想要的结果?

a = np.arange(27).reshape(3,3,3)

b = [2,2]

实际行为:

a[:,b]

array([[[ 6,  7,  8],
        [ 6,  7,  8]],

       [[15, 16, 17],
        [15, 16, 17]],

       [[24, 25, 26],
        [24, 25, 26]]])

通缉行为:

a[:,2,2]

array([ 8, 17, 26])

1 个答案:

答案 0 :(得分:3)

尝试将 : 替换为 slice(None) 并解压 b

a[(slice(None), *b)]
# [ 8 17 26]

import numpy as np

a = np.arange(27).reshape((3, 3, 3))
b = [2, 2]
result = a[(slice(None), *b)]

print(result)
# [ 8 17 26]
print((result == a[:, 2, 2]).all())
# True
相关问题