非迭代地通过AND操作将2d numpy数组转换为1d数组

2exbekwf  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(147)

我有一个形状为(1E5,2)布尔值的2d numpy数组,它的作用类似于x,y值的数组。即,1E5个项目,每个项目有2个布尔值,存储在初始2d数组中
example: [ [True, False], ..., [False, False] ]
我想把这个2d数组变成1d数组,其中[True,True]值变为True,所有其他值都为False(AND操作)。
#example: [ [True, True], [False, True], [False, False] ] --> [ True, False, False ]
为了降低walltime,我想不使用循环来做这件事。我相信单行解决方案以类似于比较的形式存在,但我自己还没有提出解决方案。
#example of what i mean by a comparison: index = positions > self.centre #(here it turns a x,y array into the 2d boolean array i currently have)
我试过:
quadIndex = positions > self.centre
positions是一个数组,保存1E5粒子的x,y值,self.centre是我正在查看的图形的当前象限的x,y坐标。创建quadIndex,它是一个2d长度=1E5布尔值(掩码?),记录粒子的x或y位置是否“通过”条件。
inQuad = np.any( ( quadIndex == np.bool_( [x, y] ) ) == [True, True] )
这一行是一个嵌套的for循环的一部分,它遍历4个象限(BL,TL,BR,TR),然后使用quadIndex的布尔值来查看该粒子是否在该象限中。当执行此检查时,我然后检查这些粒子是否导致True,True,然后检查数组中是否有任何True,True's。
我希望“流程图”:
#are you greater or lesser than the centre? eg return, [ [True, False] ]
#are you in this quadrant? (quadrant is 0,1) so return is [ [False, False] ]
#was that a [True, True]? eg, return, False
#and when the full 1E5 array is passed through this i want to end up with:
#[ True, False, ..., True ]
我现在得到:
#are you greater or lesser than the centre? eg return, [ [True, False] ]
x1米11米1x
#was that a [True]? eg, return, [False, False]

完整1E5:

#[ [False, False], [True, False], ..., [True, True] ]

0s7z1bwu

0s7z1bwu1#

只是与列:

new_arr = arr[:, 0] & arr[:, 1]

相关问题