使用多个值搜索Numpy数组

时间:2017-07-05 08:49:13

标签: python arrays numpy

我有numpy 2d数组有重复值。

我正在搜索这样的数组。

array([[1, 2, 3],
       [1, 2, 3],
       [4, 8, 9],
       [4, 2, 3],
       [5, 2, 3]])

输入是列表,其编号类似于列0值。 我想要的最终结果是任何格式的结果行,例如数组,列表或元组,例如

a[np.where(a[:,0] == l)]

我的代码工作正常,但似乎并不像pythonic。是否有更好的搜索策略有多个值?

VALIDATE statement: Verifies that a record complies with mandatory field and unique index definitions. 类似,其中只进行一次查找以获取所有值。

我的真实数组很大

2 个答案:

答案 0 :(得分:6)

方法#1:使用np.in1d -

a[np.in1d(a[:,0], num_list)]

方法#2:使用np.searchsorted -

num_arr = np.sort(num_list) # Sort num_list and get as array

# Get indices of occurrences of first column in num_list
idx = np.searchsorted(num_arr, a[:,0])

# Take care of out of bounds cases
idx[idx==len(num_arr)] = 0 

out = a[a[:,0] == num_arr[idx]]

答案 1 :(得分:1)

你可以做到

a[numpy.in1d(a[:, 0], num_list), :]