0

How can I select specific rows, where these rows equal to another row in another parallel array? in other words; can I vectorize code? here p, y are ndarray withe the same shape

for inx,val in enumerate(p):
    if val ==y[inx]:
        pprob.append(1)
    else:
        pprob.append(0)
1
  • Please post a complete MCVE Commented May 13, 2021 at 5:26

2 Answers 2

1

I just ran this in a python shell in Python 3.9.4

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([1,1,3,3,5])

matching_idx = np.where(x == y) # (array([0, 2, 4]),)

x[matching_idx] # array([1, 3, 5])

Seems like x[matching_idx] is what you want

The key to this is np.where(), explained here

Sign up to request clarification or add additional context in comments.

Comments

1
import numpy as np

a = np.random.normal(size=(10, 5))
b = np.random.normal(size=(10, 5))

a[1] = b[1]
a[7] = b[7]

rows = np.all(a == b, axis=1).astype(np.int32)
rows = rows.tolist()   # if you really want the result to be a list
print(rows)

Result as expected

[0 1 0 0 0 0 0 1 0 0]

If you could be dealing with more than two dimensions, change the following (works for 2d as well):

# this
np.all(a == b, axis=1)
# to this
np.all(a == b, axis=tuple(range(len(a.shape)))[1:])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.