我正在寻找与表类似的SQL'where'查询。我已经做了很多搜索,或者我使用了错误的搜索词或者不理解答案。可能两者都有。
所以表是二维的numpy数组。
my_array = np.array([[32, 55, 2],
[15, 2, 60],
[76, 90, 2],
[ 6, 65, 2]])
我希望以相同形状的numpy数组“结束”,例如第二列值> = 55 AND <= 65。
所以我想要的numpy数组将是...
desired_array([[32, 55, 2],
[ 6, 65, 2]])
而且,'desired_array'的顺序与'my_array'的顺序匹配吗?
只需制作并使用面具。
mask = np.logical_and(my_array[:, 1] >= 55, my_array[:, 1] <= 65)
desired_array = my_array[mask]
desired_array
一般的Numpy过滤数组的方法是创建一个与数组的所需部分匹配的“掩码”,然后使用它进行索引。
>>> my_array[((55 <= my_array) & (my_array <= 65))[:, 1]]
array([[32, 55, 2],
[ 6, 65, 2]])
打破它:
# Comparing an array to a scalar gives you an array of all the results of
# individual element comparisons (this is called "broadcasting").
# So we take two such boolean arrays, resulting from comparing values to the
# two thresholds, and combine them together.
mask = (55 <= my_array) & (my_array <= 65)
# We only want to care about the [1] element in the second array dimension,
# so we take a 1-dimensional slice of that mask.
desired_rows = mask[:, 1]
# Finally we use those values to select the desired rows.
desired_array = my_array[desired_rows]
((前两个操作可以互换,那样我想效率更高,但是对于这么小的东西来说并不重要。这种方式首先出现在我身上。)
您的意思不是相同的形状。您可能意味着相同的列大小。 my_array的形状为(4,3),所需数组的形状为(2,3)。我也建议掩盖。
您可以将filter
语句与lambda
一起使用,该语句检查每一行的期望条件以获得期望的结果:
my_array = np.array([[32, 55, 2],
[15, 2, 60],
[76, 90, 2],
[ 6, 65, 2]])
desired_array = np.array([l for l in filter(lambda x: x[1] >= 55 and x[1] <= 65, my_array)])
运行此文件,我们得到:
>>> desired_array
array([[32, 55, 2],
[ 6, 65, 2]])