Ahmed Adel
Ahmed Adel

Reputation: 21

Conditional slicing in python

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)

Upvotes: 0

Views: 290

Answers (2)

Reti43
Reti43

Reputation: 9797

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:])

Upvotes: 1

Joshua Swain
Joshua Swain

Reputation: 690

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

Upvotes: 1

Related Questions