我有这个数组:
arr = np.array([[[ -1., -1., -1., 0., 0., 0.],
[ 0.1, 0.1, 0.1, 2., 3., 4.]], # <-- this one
[[ -1., -1., -1., 0., 0., -1.],
[ 0.1, 0.1, 0.1, 16., 17., 0.1]], # <-- and this one
[[ -1., -1., -1., 0., 0., 0.],
[ 0.1, 0.1, 0.1, 4., 5., 6.]], # <-- and this one
[[ 0., 0., 0., -1., 0., 0.],
[ 1., 2., 3., 0.1, 1., 2.]], # <-- and this one
[[ -1., -1., 0., 0., 0., 0.],
[ 0.1, 0.1, 1., 9., 10., 11.]]]) # <-- and the last one
我想提取每个数组中的第2个数组,结果应该如下:
res = [[ 0.1, 0.1, 0.1, 2., 3., 4.],
[ 0.1, 0.1, 0.1, 16., 17., 0.1],
[ 0.1, 0.1, 0.1, 4., 5., 6.],
[ 1., 2., 3., 0.1, 1., 2.],
[ 0.1, 0.1, 1., 9., 10., 11.]]
我想在一行代码中获取res
,我试过了但是没有成功
arr[:][1] # select the element 1 in each array
# I got
array([[ -1. , -1. , -1. , 0. , 0. , -1. ],
[ 0.1, 0.1, 0.1, 16. , 17. , 0.1]])
谁能解释一下为什么?
我找到的唯一解决方案是明确指示每个索引 (arr[0][1]...
),我不喜欢这样。
最佳答案
这是一个 3D
数组,您正试图选择第二个轴的第二个元素并提取其余轴上的所有元素。所以,它很简单——
arr[:,1,:]
我们可以跳过列出尾随轴的 :
,因此它进一步简化为 -
arr[:,1]
sample 运行-
In [360]: arr
Out[360]:
array([[[ -1. , -1. , -1. , 0. , 0. , 0. ],
[ 0.1, 0.1, 0.1, 2. , 3. , 4. ]],
[[ -1. , -1. , -1. , 0. , 0. , -1. ],
[ 0.1, 0.1, 0.1, 16. , 17. , 0.1]],
[[ -1. , -1. , -1. , 0. , 0. , 0. ],
[ 0.1, 0.1, 0.1, 4. , 5. , 6. ]],
[[ 0. , 0. , 0. , -1. , 0. , 0. ],
[ 1. , 2. , 3. , 0.1, 1. , 2. ]],
[[ -1. , -1. , 0. , 0. , 0. , 0. ],
[ 0.1, 0.1, 1. , 9. , 10. , 11. ]]])
In [361]: arr[:,1]
Out[361]:
array([[ 0.1, 0.1, 0.1, 2. , 3. , 4. ],
[ 0.1, 0.1, 0.1, 16. , 17. , 0.1],
[ 0.1, 0.1, 0.1, 4. , 5. , 6. ],
[ 1. , 2. , 3. , 0.1, 1. , 2. ],
[ 0.1, 0.1, 1. , 9. , 10. , 11. ]])
关于python - 从数组的数组中提取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634508/