Python 每列的numpy索引
我想通过为每列建立索引来从数组中获取项。 例如,索引如下:Python 每列的numpy索引,python,numpy,Python,Numpy,我想通过为每列建立索引来从数组中获取项。 例如,索引如下: [[1, 3], [2, 4]] 这意味着: 获取数组第0列的第1和第2个元素,并将它们放入结果的第0列 获取数组第一列的第三和第四个元素,并将它们放入结果的第一列 节目: 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.
[[1, 3],
[2, 4]]
这意味着:
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)
结果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[[1 1 1 1]
[6 6 6 6]]]
[[[ 4 5 6 7]]
[[ 8 9 10 11]]]
预期结果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[[4 5 6 7]
[8 9 10 11]]]
如何获得预期的结果?这项工作:
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)
结果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[[1 1 1 1]
[6 6 6 6]]]
[[[ 4 5 6 7]]
[[ 8 9 10 11]]]
这项工作:
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)
结果:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[[1 1 1 1]
[6 6 6 6]]]
[[[ 4 5 6 7]]
[[ 8 9 10 11]]]
但我不知道为什么。我明白了。它只是在右轴上广播。但我不知道为什么。好的。我明白了。它只是在右轴上广播。