在python中访问第n维 [英] Access n-th dimension in python
问题描述
我想要对多维 numpy 数组的某些部分进行易于阅读的访问.对于任何数组,访问第一维都很容易(b[index]
).另一方面,访问第六维是困难的"(尤其是阅读).
I want a easy to read access to some parts of a multidimensional numpy array. For any array accessing the first dimension is easy (b[index]
). Accessing the sixth dimension on the other hand is "hard" (especially to read).
b[:,:,:,:,:,index] #the next person to read the code will have to count the :
有没有更好的方法来做到这一点?特别是有没有办法,在编写程序时不知道轴?
Is there a better way to do this? Especially is there a way, where the axis is not known while writing the program?
索引维度不一定是最后一个维度
The indexed dimension is not necessarily the last dimension
推荐答案
如果你想要一个视图并且想要它快速,你可以手动创建索引:
If you want a view and want it fast you can just create the index manually:
arr[(slice(None), )*5 + (your_index, )]
# ^---- This is equivalent to 5 colons: `:, :, :, :, :`
它比 np.take
快得多,并且只比使用 :
s:
Which is much faster than np.take
and only marginally slower than indexing with :
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)
但可能不那么可读,所以如果你经常需要,你可能应该把它放在一个具有有意义名称的函数中:
But maybe not as readable, so if you need that often you probably should put it in a function with a meaningful name:
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)
这篇关于在python中访问第n维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!