两列不同维度的numpy数组的交集

时间:2022-07-19 12:07:36

I have two different numpy arrays given. First one is two-dimensional array which looks like (first ten points):

我给出了两个不同的numpy数组。第一个是二维数组,看起来像(前十点):

[[  0.           0.        ]
 [ 12.54901961  18.03921569]
 [ 13.7254902   17.64705882]
 [ 14.11764706  17.25490196]
 [ 14.90196078  17.25490196]
 [ 14.50980392  17.64705882]
 [ 14.11764706  17.64705882]
 [ 14.50980392  17.25490196]
 [ 17.64705882  18.03921569]
 [ 21.17647059  34.11764706]]

the second array is just one-dimensional which looks like (first ten points):

第二个数组只是一维的,看起来像(前十点):

[ 18.03921569  17.64705882  17.25490196  17.25490196  17.64705882
  17.64705882  17.25490196  17.64705882  21.17647059  22.35294118]

Values from the second (one-dimension) array could occur in first (two-dimension) one in the first column. F.e. 17.64705882

第二个(一维)数组中的值可能出现在第一列中的第一个(二维)数组中。 F.E. 17.64705882

I want to get an array from the two-dimension one where values of the first column match values in the second (one-dimension) array. How to do that?

我想从二维数组中获取一个数组,其中第一列的值与第二个(一维)数组中的值匹配。怎么做?

1 个解决方案

#1


5  

You can use np.in1d(array1, array2) to search in array1 each value of array2. In your case you just have to take the first column of the first array:

您可以使用np.in1d(array1,array2)在array1中搜索array2的每个值。在您的情况下,您只需要获取第一个数组的第一列:

mask = np.in1d(a[:, 0], b)
#array([False, False, False, False, False, False, False, False,  True,  True], dtype=bool)

You can use this mask to obtain the encountered values:

您可以使用此掩码来获取遇到的值:

a[:, 0][mask]
#array([ 17.64705882,  21.17647059])

#1


5  

You can use np.in1d(array1, array2) to search in array1 each value of array2. In your case you just have to take the first column of the first array:

您可以使用np.in1d(array1,array2)在array1中搜索array2的每个值。在您的情况下,您只需要获取第一个数组的第一列:

mask = np.in1d(a[:, 0], b)
#array([False, False, False, False, False, False, False, False,  True,  True], dtype=bool)

You can use this mask to obtain the encountered values:

您可以使用此掩码来获取遇到的值:

a[:, 0][mask]
#array([ 17.64705882,  21.17647059])