Jür*_*aak 3 python arrays indexing numpy multidimensional-array
我想要一个易于读取访问多维numpy数组的某些部分.对于任何访问第一个维度的数组都是easy(b[index]).另一方面,访问第六维是"硬"(特别是阅读).
b[:,:,:,:,:,index] #the next person to read the code will have to count the :
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?特别是有一种方法,在编写程序时轴是不知道的吗?
编辑:索引维度不一定是最后一个维度
如果您想要一个视图并且想要快速查看,您可以手动创建索引:
arr[(slice(None), )*5 + (your_index, )]
# ^---- This is equivalent to 5 colons: `:, :, :, :, :`
Run Code Online (Sandbox Code Playgroud)
它np.take比使用:s 索引快得多,并且仅慢一点:
import numpy as np
arr = np.random.random((10, 10, 10, 10, 10, 10, 10))
np.testing.assert_array_equal(arr[:,:,:,:,:,4], arr.take(4, axis=5))
np.testing.assert_array_equal(arr[:,:,:,:,:,4], arr[(slice(None), )*5 + (4, )])
%timeit arr.take(4, axis=5)
# 18.6 ms ± 249 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit arr[(slice(None), )*5 + (4, )]
# 2.72 µs ± 39.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit arr[:, :, :, :, :, 4]
# 2.29 µs ± 107 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Run Code Online (Sandbox Code Playgroud)
但是可能不那么易读,因此,如果经常需要,您可能应该将其放在具有有意义名称的函数中:
def index_axis(arr, index, axis):
return arr[(slice(None), )*axis + (index, )]
np.testing.assert_array_equal(arr[:,:,:,:,:,4], index_axis(arr, 4, axis=5))
%timeit index_axis(arr, 4, axis=5)
# 3.79 µs ± 127 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Run Code Online (Sandbox Code Playgroud)
MSeifert 和 Kazemakase 的答案之间的中间方法(在可读性和时间方面)正在使用np.rollaxis:
np.rollaxis(b, axis=5)[index]\nRun Code Online (Sandbox Code Playgroud)\n\n测试解决方案:
\n\nimport numpy as np\n\narr = np.random.random((10, 10, 10, 10, 10, 10, 10))\n\nnp.testing.assert_array_equal(arr[:,:,:,:,:,4], arr.take(4, axis=5))\nnp.testing.assert_array_equal(arr[:,:,:,:,:,4], arr[(slice(None), )*5 + (4, )])\nnp.testing.assert_array_equal(arr[:,:,:,:,:,4], np.rollaxis(arr, 5)[4])\n\n%timeit arr.take(4, axis=5)\n# 100 loops, best of 3: 4.44 ms per loop\n%timeit arr[(slice(None), )*5 + (4, )]\n# 1000000 loops, best of 3: 731 ns per loop\n%timeit arr[:, :, :, :, :, 4]\n# 1000000 loops, best of 3: 540 ns per loop\n%timeit np.rollaxis(arr, 5)[4]\n# 100000 loops, best of 3: 3.41 \xc2\xb5s per loop\nRun Code Online (Sandbox Code Playgroud)\n