Reputation: 11
I am working on some molecular dynamics using Python, and the arrays tend to get pretty large. It would be helpful to have a quick check to see if certain vectors appear in the arrays. After searching for way to do this, I was surprised to see this question doesn't seem to come up. In particular, if I have something like
import numpy as np
y = [[1,2,3], [1,3,2]]
x = np.array([[1,2,3],[3,2,1],[2,3,1],[10,5,6]])
and I want to see if the specific vectors from y are present in x (not just the elements), how would I do so? Using something like
for i in y:
if i in x:
print(i)
will simply return every y array vector that contains at least one element of i. Thoughts?
Upvotes: 1
Views: 92
Reputation: 53089
The best strategy will depend on sizes and numbers. A quick solution is
[np.where(np.all(x==row, axis=-1))[0] for row in y]
# [array([0]), array([], dtype=int64)]
The result list gives for each row in y a possibly empty array of positions in x where the row occurs.
Upvotes: 0
Reputation: 77860
You don't explicitly give your expected output, but I infer that you want to see only [1, 2, 3] as the output from this program.
You get that output if you make x merely another list, rather than a NumPy array.
Upvotes: 0
Reputation: 2414
If you want to check if ALL vectors in y
are present in the array, you could try:
import numpy as np
y = [[1,2,3], [1,3,2]]
x = np.array([[1,2,3],[3,2,1],[2,3,1],[10,5,6]])
all(True if i in x else False for i in y)
# True
Upvotes: 1