简体   繁体   English

创建一个 3d numpy 数组,其条目在给定方向上增加

[英]Create a 3d numpy array whose entries increase in the given direction

Given a shape (n,m,k) and a nonzero vector (u,v,w) with entries in {-1,0,1}, I would like to create a numpy array of shape (n,m,k).给定一个形状 (n,m,k) 和一个非零向量 (u,v,w) 的条目在 {-1,0,1} 中,我想创建一个形状为 (n,m,k) 的 numpy 数组. The entries of the array should start at 1 and increase in the direction of the vector.数组的条目应该从 1 开始,并在向量的方向上增加。

Although I am specifically asking for 3d arrays, let me illustrate with 2d examples:虽然我特别要求使用 3d 数组,但让我用 2d 示例进行说明:

(n,m) = (3,4) and (u,v) = (-1,0) gives:

4 3 2 1
4 3 2 1
4 3 2 1

(n,m) = (4,3) and (u,v) = (1,-1) gives:

1 2 3
2 3 4
3 4 5
4 5 6

I can create them using nested for loops, but I am wondering if there is a faster solution since I will be working with larger arrays.我可以使用嵌套的 for 循环创建它们,但我想知道是否有更快的解决方案,因为我将使用更大的数组。

Here is a method using stride_tricks .这是使用stride_tricks的方法。 Works for arbitrary number of dimensions.适用于任意数量的维度。

from numpy.lib.stride_tricks import as_strided                    

def pp(dims,strides):                                                      
    dims,strides = np.asarray(dims),np.asarray(strides)                    
    aux = np.arange(1,(dims-1).sum()+2)                                    
    return as_strided(aux[(dims-1)@(strides==-1):],dims,aux.strides*strides)

Examples:例子:

>>> pp((2,3),(-1,0))
array([[2, 2, 2],
       [1, 1, 1]])
>>> pp((2,3,4),(-1,-1,-1))
array([[[7, 6, 5, 4],
        [6, 5, 4, 3],
        [5, 4, 3, 2]],

       [[6, 5, 4, 3],
        [5, 4, 3, 2],
        [4, 3, 2, 1]]])

Note that the convention for y-axis is it starts at top and goes down.请注意,y 轴的约定是从顶部开始并向下。 If you want otherwise you'd have to flip it.如果你想要,否则你必须翻转它。

Also note that the arrays produced are non-contiguous views, if you want to modify them better make a copy.另请注意,生成的数组是非连续视图,如果您想修改它们,最好制作一个副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM