使用numpy创建特定的数组

时间:2017-10-03 12:24:08

标签: python numpy

我想用numpy创建这种数组:

[[[0,0,0], [1,0,0], ..., [1919,0,0]],
 [[0,1,0], [1,1,0], ..., [1919,1,0]],
 ...,
 [[0,1019,0], [1,1019,0], ..., [1919,1019,0]]]

我可以通过以下方式访问:

>>> data[25][37]
array([25, 37, 0])

我试图以这种方式创建一个数组,但它还没有完成:

>>> data = np.mgrid[0:1920:1, 0:1080:1].swapaxes(0,2).swapaxes(0,1)
>>> data[25][37]
array([25, 37])

你知道怎么用numpy解决这个问题吗?

2 个答案:

答案 0 :(得分:5)

方法#1:这是console.log(this.props.surveys)np.ogrid的一种方式 -

array-initialization

示例运行 -

def indices_zero_grid(m,n):
    I,J = np.ogrid[:m,:n]
    out = np.zeros((m,n,3), dtype=int)
    out[...,0] = I
    out[...,1] = J
    return out

方法#2: @senderle's cartesian_product的修改,并受到@unutbu's modification to it的启发 -

In [550]: out = indices_zero_grid(1920,1080)

In [551]: out[25,37]
Out[551]: array([25, 37,  0])

运行时测试 -

import functools
def indices_zero_grid_v2(m,n):
    """
    Based on cartesian_product
    http://stackoverflow.com/a/11146645 (@senderle)
    Inspired by : https://stackoverflow.com/a/46135435 (@unutbu)
    """
    shape = m,n
    arrays = [np.arange(s, dtype='int') for s in shape]
    broadcastable = np.ix_(*arrays)
    broadcasted = np.broadcast_arrays(*broadcastable)
    rows, cols = functools.reduce(np.multiply, broadcasted[0].shape), \
                                                  len(broadcasted)+1
    out = np.zeros(rows * cols, dtype=int)
    start, end = 0, rows
    for a in broadcasted:
        out[start:end] = a.reshape(-1)
        start, end = end, end + rows
    return out.reshape(-1,m,n).transpose(1,2,0)

答案 1 :(得分:5)

In [50]: data = np.mgrid[:1920, :1080, :1].transpose(1,2,3,0)[..., 0, :]

In [51]: data[25][37]
Out[51]: array([25, 37,  0])

请注意,data[25][37]两次调用__getitem__。使用NumPy阵列,您可以使用__getitem__更有效地访问相同的值(通过一次调用data[25, 37]):

In [54]: data[25, 37]
Out[54]: array([25, 37,  0])