访问python中的第n个维度 [英] Access n-th dimension in python

查看:127
本文介绍了访问python中的第n个维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够轻松读取多维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: `:, :, :, :, :`

这比<$ c $要快得多c> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆