I have an array c
, another array d
. how can I check if d[1]
ord[3]
ord[5]
ord[7]
is in array c
?
c = np.array([[ 1, 1,0],
[ 1,-1,0],
[-1, 1,0],
[-1,-1,0]])
d = np.array([[2,2,2],
[1,1,0],
[2,8,8],
[6,8,8],
[2,2,2],
[4,9,0],
[2,2,2],
[3,2,2]])
I tried g = np.any(c == d[1,3,5,7])
,but it doesn't work. In this case, the result should be True
because [1,1,0] is in array c
. Can anyone help me?
CodePudding user response:
As you are using numpy use the function isin
that is defined:
EDIT: you changed the question, but the answer is equally valid. Here it is how to check all d in c: import numpy as np
c = np.array([[ 1, 1,0],
[ 1,-1,0],
[-1, 1,0],
[-1,-1,0]])
d = np.array([[2,2,2],
[1,1,0],
[2,8,8],
[6,8,8],
[2,2,2],
[4,9,0],
[2,2,2],
[3,2,2]])
for item in d:
g = np.isin(item,c).all()
print(g)
If you want a particular array in d use the formula without the for, just put d[0],d
CodePudding user response:
Try this
# to check if a row in its entirety match a list,
# use all on axis=1 first, then check if any rows match using any
(c==[2,1,0]).all(1).any()
False
For multiple checks
# use bit-wise | (instead of or)
((c==[2,1,0]) | (c==[3,1,0]) | (c==[5,5,0])).all(1).any()
CodePudding user response:
The direct way should be to compare one by one:
any(any((i == j).all() for j in c) for i in d[1::2])
Or use one or two layers of Broadcasting:
any((c == i).all(-1).any() for i in d[1::2])
(c[:, None] == d[None, 1::2]).all(-1).any()
Using broadcast can calculate faster, but it must first calculate all the comparison results, and then check them with method ndarray.any
, but loop check can reduce the number of comparisons.
In addition, np.isin
can't meet your requirements. It only returns whether each element of first parameter is in the second parameter.