python - 使用 numpy 创建特定数组

标签 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 解决这个问题吗?

最佳答案

方法 #1:这是使用 np.ogridarray-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

sample 运行-

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

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

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

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)

运行时测试-

In [2]: %timeit indices_zero_grid(1920,1080)
100 loops, best of 3: 8.4 ms per loop

In [3]: %timeit indices_zero_grid_v2(1920,1080)
100 loops, best of 3: 8.14 ms per loop

关于python - 使用 numpy 创建特定数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544554/

相关文章:

列表中项目的Python索引没有错误?

python - 如何在 python 抽象类中创建抽象属性

python - DataFrame 列中的混合类型元素

python - 如何在 keras 生成器中使用 numpy memmap 不超过 RAM 内存?

python - 动态添加类成员使用字符串命名

python - 为什么 -1/2 在 C++ 中评估为 0,但在 Python 中评估为 -1?

python - 在不安装 graphlab 的情况下在 SFrame 中分组

python - 在某些位置添加子矩阵

python - 值错误: matrix must be 2-dimensional when passing two arrays to the function

pandas - 如何从频率表创建箱线图