python - 从一维 NumPy 数组创建二维掩码

标签 python numpy

我想从 numpy 数组的行中获取前 n 个值,其中 n 在单独的一维数组中指定:

import numpy as np

a = np.zeros((5, 5))
n = [1, 3, 2, 4, 1]

result = [[1, 0, 0, 0, 0],
          [1, 1, 1, 0, 0],
          [1, 1, 0, 0, 0],
          [1, 1, 1, 1, 0],
          [1, 0, 0, 0, 0]]

我正在寻找不需要迭代的解决方案,因为结果数组将有数百万行。

最佳答案

在利用 broadcasting 时,对范围数组使用 n 的外部比较创建掩码,从而创建最终数组 -

ncols = 5
mask_out = np.greater.outer(n,np.arange(ncols))

sample 运行-

In [19]: n = [1, 3, 2, 4, 1]

In [9]: ncols = 5

# Output as mask
In [10]: np.greater.outer(n,np.arange(ncols))
Out[10]: 
array([[ True, False, False, False, False],
       [ True,  True,  True, False, False],
       [ True,  True, False, False, False],
       [ True,  True,  True,  True, False],
       [ True, False, False, False, False]])

# Output as array of 0s and 1s
In [11]: np.greater.outer(n,np.arange(ncols)).view('i1')
Out[11]: 
array([[1, 0, 0, 0, 0],
       [1, 1, 1, 0, 0],
       [1, 1, 0, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 0, 0, 0, 0]], dtype=int8)

如果你必须填充一个已经初始化的数组 result,只需使用 mask_out 来屏蔽数组,即 result[mask_out] = ....

关于python - 从一维 NumPy 数组创建二维掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55190295/

相关文章:

python - Matplotlib 中的图像处理

android - 如何在kivy中像youtube一样播放来自网络的视频

python - 将一个 pandas 数据帧分配为另一个 pandas 数据帧的子帧

python - 将 Numpy 数组中的一个 channel 广播为三个 channel

python - Python 中的快速逆矩阵和转置矩阵

numpy - 在 Deepnote 中运行 ImageDataBunch 时出现问题

python - 从由 "#"分隔的行值中提取最小值和最大值

python - Django中2个模型之间的关系

python - Getting Started with Python on Heroku - Run the app locally 步骤问题

python - 在 numpy 中查找最大值的索引排除零值