python - 通过 int 选择 numpy 数组轴

标签 python arrays numpy multidimensional-array

我正在尝试系统地访问 numpy 数组的轴。例如,假设我有一个数组

a = np.random.random((10, 10, 10, 10, 10, 10, 10))
# choosing 7:9 from axis 2
b = a[:, :, 7:9, ...]
# choosing 7:9 from axis 3
c = a[:, :, :, 7:9, ...]

如果我有一个高维数组,输入冒号会变得非常重复。现在,我想要一些函数 choose_from_axis 这样

# choosing 7:9 from axis 2
b = choose_from_axis(a, 2, 7, 9)
# choosing 7:9 from axis 3
c = choose_from_axis(a, 3, 7, 9)

所以,基本上,我想访问一个带有数字的轴。我知道如何做到这一点的唯一方法是来回使用 rollaxis,但我正在寻找一种更直接的方法来做到这一点。

最佳答案

听起来您可能正在寻找 take :

>>> a = np.random.randint(0,100, (3,4,5))
>>> a[:,1:3,:]
array([[[61,  4, 89, 24, 86],
        [48, 75,  4, 27, 65]],

       [[57, 55, 55,  6, 95],
        [19, 16,  4, 61, 42]],

       [[24, 89, 41, 74, 85],
        [27, 84, 23, 70, 29]]])
>>> a.take(np.arange(1,3), axis=1)
array([[[61,  4, 89, 24, 86],
        [48, 75,  4, 27, 65]],

       [[57, 55, 55,  6, 95],
        [19, 16,  4, 61, 42]],

       [[24, 89, 41, 74, 85],
        [27, 84, 23, 70, 29]]])

这也将为您提供对元组索引的支持。示例:

>>> a = np.arange(2*3*4).reshape(2,3,4)
>>> a
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> a[:,:,(0,1,3)]
array([[[ 0,  1,  3],
        [ 4,  5,  7],
        [ 8,  9, 11]],

       [[12, 13, 15],
        [16, 17, 19],
        [20, 21, 23]]])
>>> a.take((0,1,3), axis=2)
array([[[ 0,  1,  3],
        [ 4,  5,  7],
        [ 8,  9, 11]],

       [[12, 13, 15],
        [16, 17, 19],
        [20, 21, 23]]])

关于python - 通过 int 选择 numpy 数组轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067183/

相关文章:

Javascript: indexOf($(this) 获取点击元素的数组索引值?

python - numpy.linalg.LinAlgError : SVD did not converge in Linear Least Squares on first run only

Python - Pandas - 将 YYYYMM 转换为日期时间

python - 如何使用 Python 获取请求中响应的原始内容?

python - 关于 GUI 计时器的建议,以显示后台线程的运行时间?

HTML 表单 : POST an array of objects

java - 将对象添加到具有排除的数组

python - 为大对象分配名称似乎会大大增加内存使用量

python - python 中的数组/图像插值

python - Seaborn 条形图中的垂直线代表什么?