1

I have 2 arrays as follow:

l=
array([[1205, 1420, 1340],
       [1306, 1530, 1045],
       [2001, 135, 1207],
               ...]])

y= 
array([[1200, 1320, 2001],
       [1306, 1530, 1045],
              ...,
       [  0,   3,   0]])

I would like to find the fastest way to replace values (the sub arrays) in l that are in y by [1000,1000,1000].

for example I would get:

 l=
array([[1205, 1420, 1340],
   [1000, 1000, 1000],
   [2001, 135, 1207],
           ...]])

So far I've tried a 'for' loop with 'if' condition but it takes too much time.

Thanks for your suggestions.

4
  • can you include the actual code you've tried? Commented Aug 21, 2018 at 15:07
  • Do you want subarrays anywhere in y? Or only check for matching corresponding rows. Commented Aug 21, 2018 at 15:15
  • the suggested solution worked for me thank you @user3483203 Commented Aug 21, 2018 at 15:20
  • @hdatas Would still be better to clarify as the posted solution searches for a match across all rows in y. Commented Aug 21, 2018 at 15:23

1 Answer 1

4

We could use views to view each row as one element, then use np.isin to get a boolean array of presence, use it to index and finally assign -

# https://stackoverflow.com/a/45313353/ @Divakar
def view1D(a, b): # a, b are arrays
    a = np.ascontiguousarray(a)
    b = np.ascontiguousarray(b)
    void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))
    return a.view(void_dt).ravel(),  b.view(void_dt).ravel()

l1D,y1D = view1D(l,y)
l[np.isin(l1D, y1D)] = [1000,1000,1000]

Sample run -

In [36]: l
Out[36]: 
array([[1205, 1420, 1340],
       [1306, 1530, 1045],
       [2001,  135, 1207],
       [   2,    3,    4]])

In [37]: y
Out[37]: 
array([[1200, 1320, 2001],
       [1306, 1530, 1045],
       [   0,    3,    0]])

In [38]: l1D,y1D = view1D(l,y)

In [39]: l[np.isin(l1D, y1D)] = [1000,1000,1000]

In [40]: l
Out[40]: 
array([[1205, 1420, 1340],
       [1000, 1000, 1000],
       [2001,  135, 1207],
       [   2,    3,    4]])
Sign up to request clarification or add additional context in comments.

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.