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



我有一个形状为(1E5, 2)的布尔值的二维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 ]

为了减少运行时间,我想在不使用循环的情况下这样做。我相信单行解决方案以类似于比较的形式存在,但我自己还没有想出一个解决方案。

#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个粒子和self的x、y值的数组。中心是图像当前象限的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我希望"流程图"

#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 ]

i current get:

#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]? eg, return, [False, False]

# 1 e5:

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

只是和列:

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

最新更新