繁体   English   中英

Numpy 数组:如何根据列中的值提取整行

[英]Numpy array: How to extract whole rows based on values in a column

我正在寻找等效于表的 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)。 我也建议屏蔽。

您可以使用带有lambdafilter语句来检查每一行的所需条件以获得所需的结果:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM