Python Numpy数组:如何基于列中的值提取整行
我正在寻找表上SQL“where”查询的等价物。我做了很多搜索,要么使用了错误的搜索词,要么不理解答案。可能两者都有 所以一个表是一个二维numpy数组Python Numpy数组:如何基于列中的值提取整行,python,numpy-ndarray,Python,Numpy Ndarray,我正在寻找表上SQL“where”查询的等价物。我做了很多搜索,要么使用了错误的搜索词,要么不理解答案。可能两者都有 所以一个表是一个二维numpy数组 my_array = np.array([[32, 55, 2], [15, 2, 60], [76, 90, 2], [ 6, 65, 2]]) 我希望以相同形状的numpy数组“结束”,例如第二列值>=
my_array = np.array([[32, 55, 2],
[15, 2, 60],
[76, 90, 2],
[ 6, 65, 2]])
我希望以相同形状的numpy数组“结束”,例如第二列值>=55和您可以使用带有
lambda
的filter
语句来检查每一行的所需条件,以获得所需结果:
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)])
做一个面具,然后用它
mask = np.logical_and(my_array[:, 1] >= 55, my_array[:, 1] <= 65)
desired_array = my_array[mask]
desired_array
mask=np.logical_and(my_array[:,1]>=55,my_array[:,1]过滤数组的一般Numpy方法是创建一个与数组所需部分匹配的“mask”,然后使用它进行索引
>>> my_array[((55 <= my_array) & (my_array <= 65))[:, 1]]
array([[32, 55, 2],
[ 6, 65, 2]])
>>我的数组[((55你不是指相同的形状。你可能是指相同的列大小。我的数组的形状是(4,3),你想要的数组的形状是(2,3)。我也建议您使用掩蔽。如果您使用列表理解来操作numpy数组,那么您就违背了使用numpy的目的。Gilseung Ahn哇!这很快就正确了。非常感谢您。在我的大量搜索中,我从未遇到过类似的情况。
mask = np.logical_and(my_array[:, 1] >= 55, my_array[:, 1] <= 65)
desired_array = my_array[mask]
desired_array
>>> 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]