如何为多维NumPy数组创建布尔索引数组?

时间:2023-01-18 21:21:49

I'm looking at this question: Efficient thresholding filter of an array with numpy

我正在看这个问题:一个有numpy的数组的高效阈值过滤器

I have a similar problem, but with a two dimensional array, where several coordinates and values are stored in rows of a NumPy array. How I can do a similar filtering like in the question above?

我有一个类似的问题,但有一个二维数组,其中几个坐标和值存储在NumPy数组的行中。如何在上面的问题中进行类似的过滤?

My data looks like this:

我的数据如下所示:

>>> A.shape
(4269862, 5)

>>> A[0]
array([  2.27011719e+02,   0.00000000e+00,   2.88134766e+02,
         2.00000000e+00,   7.69880000e+04], dtype=float32)

And these values correspond to X, Y, Z and value1 and value2. What I want is to efficiently get eg. all rows with X in 300--400, Y in 200--250 and Z in 200--300.

这些值对应于X,Y,Z和value1和value2。我想要的是有效地获得例如。所有行的X在300-400,Y在200-250,Z在200-300。

1 个解决方案

#1


2  

You can create a boolean mask that will be true when all your conditions are met:

您可以创建一个布尔掩码,当满足所有条件时,该掩码将为true:

idx = ((A[:, 0] > 300) & (A[:, 0] < 400) & 
       (A[:, 1] > 200) & (A[:, 1] < 250) & 
       (A[:, 2] > 200) & (A[:, 2] < 300))

print A[idx]   
# this should give your array rows where idx is True

You can test this:

你可以测试一下:

A = np.random.uniform(150, 500, (200, 5)).astype('i')
idx = ((A[:, 0] > 300) & (A[:, 0] < 400) & 
       (A[:, 1] > 200) & (A[:, 1] < 250) & 
       (A[:, 2] > 200) & (A[:, 2] < 300))
print A[idx]
#[[339 292 231 211 474]
# [371 252 310 281 256]
# [337 263 471 159 397]
# [361 299 383 250 206]
# [360 278 328 194 453]
# [360 258 205 245 427]
# [339 286 331 175 418]]

#1


2  

You can create a boolean mask that will be true when all your conditions are met:

您可以创建一个布尔掩码,当满足所有条件时,该掩码将为true:

idx = ((A[:, 0] > 300) & (A[:, 0] < 400) & 
       (A[:, 1] > 200) & (A[:, 1] < 250) & 
       (A[:, 2] > 200) & (A[:, 2] < 300))

print A[idx]   
# this should give your array rows where idx is True

You can test this:

你可以测试一下:

A = np.random.uniform(150, 500, (200, 5)).astype('i')
idx = ((A[:, 0] > 300) & (A[:, 0] < 400) & 
       (A[:, 1] > 200) & (A[:, 1] < 250) & 
       (A[:, 2] > 200) & (A[:, 2] < 300))
print A[idx]
#[[339 292 231 211 474]
# [371 252 310 281 256]
# [337 263 471 159 397]
# [361 299 383 250 206]
# [360 278 328 194 453]
# [360 258 205 245 427]
# [339 286 331 175 418]]