获取 numpy 数组中第 k 维的第 i 个切片 [英] get the i-th slice of the k-th dimension in a numpy array

查看:51
本文介绍了获取 numpy 数组中第 k 维的第 i 个切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 n 维的 numpy 数组,我想获得 k-th 的 i-th 切片尺寸.一定有比

I have an n-dimensional numpy array, and I'd like to get the i-th slice of the k-th dimension. There must be something better than

# ... 
elif k == 5:
    b = a[:, :, :, :, :, i, ...]
# ...

推荐答案

b = a[(slice(None),) * k + (i,)]

手动构建索引元组.

Python 语言参考中所述,表格

a[:, :, :, :, :, i]

转换为

a[(slice(None), slice(None), slice(None), slice(None), slice(None), i)]

我们可以通过直接构建元组而不是使用切片符号来实现相同的效果.(有一点需要注意的是,对于 k=0,构建元组会直接生成 a[(i,)] 而不是 a[i],但 NumPy 对标量 i 的处理方式相同.)

We can achieve the same effect by building that tuple directly instead of using slicing notation. (There's the minor caveat that building the tuple directly produces a[(i,)] instead of a[i] for k=0, but NumPy handles these the same for scalar i.)

这篇关于获取 numpy 数组中第 k 维的第 i 个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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