python - Numpy根据mask生成全局数组的子集

标签 python numpy where-clause mask

我有兴趣根据使用 numpy 的匹配 bool 掩码从全局二维数组生成 np.arrays 的列表(或 np.array),用于特定轴。我想知道是否可以使用 np.ma.mask() 或类似的...

举个例子可能更好:

number= 10
x = np.linspace(0,number,num=number+1,dtype=int)
B = np.vstack((x%3==0, x%2==0, x%1==0))
X = np.vstack((x//3, x//2, x-1))

list_ = []
for i in range(1,number+1):
    pointer = X[:,i][B[:,i]]
    list_.append(pointer)

print(list_)
[array([0]), array([1, 1]), array([1, 2]), array([2, 3]), array([4]), array([2, 3, 5]), array([6]), array([4, 7]), array([3, 8]), array([5, 9])]

在 for 循环中,我基本上是基于 bool 掩码 B 在二维数组 X 中提取 axis=1 上的值。我通过遍历 axis=0 并选择 X[:,i][ 来实现此目的双]]。我想知道是否可以在没有循环的情况下执行此操作,因为范围可能非常大,并且完全在 numpy 中执行,也许在 np.ma.array(X,mask=B) 上使用 where 语句?

干杯!

最佳答案

以下是我将遵循的以矢量化方式解决案例的步骤 -

  1. 使用 bool 索引X中选择有效元素。
  2. 获取我们看到列索引为输入掩码移动的索引。这将在转置掩码后实现,使用 np.where 并选择第一个输入参数。
  3. 最后,使用这些索引,拆分在步骤 1 中获得的有效元素数组。

实现看起来像这样-

cut_idx = np.unique(np.where(B[:,1:].T)[0],return_index=True)[1]
out_list_ = np.split(X[:,1:].T[B[:,1:].T],cut_idx[1:])

关于python - Numpy根据mask生成全局数组的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904051/

相关文章:

python - Jupyter 中的 "No Module Named"错误

python - 检索数组中每个项目的元素

python - Numpy - 导入错误 : cannot import name _distributor_init

python - 返回一维 NumPy 数组中唯一值索引的代码的说明

php - Zend 多个 where

python - 解析 SQL 查询文本以提取使用的表名称

python - 如何在 numpy 数组中随机洗牌 "tiles"

c# - 为什么在方法定义中使用 "Where"子句

arrays - 当一个数组是另一个数组的元素时如何限制它的元素类型

python - 如何使用python抓取aspx呈现的页面