带有列表的 Numpy 切片
Numpy slicing with list
我正在尝试用列表 b
分割 Ndarray a
。但是行为并不像我期望的那样。我必须更改什么才能获得想要的结果?
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])
尝试将 :
替换为 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
我正在尝试用列表 b
分割 Ndarray a
。但是行为并不像我期望的那样。我必须更改什么才能获得想要的结果?
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])
尝试将 :
替换为 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