0

I would like to index ndarray in a tuple using a boolean mask such as below

import numpy as np
n_max = 5
list_no = np.arange ( 0, n_max )
lateral = np.tril_indices ( n_max, -1 )
mask= np.diff ( lateral [0].astype ( int ) )
mask [-1] = 1
Expected=lateral[mask!= 0]

However, when executing the line Expected=lateral[mask!= 0], the compiler return an error

TypeError: only integer scalar arrays can be converted to a scalar index

Expected=
0 = {ndarray: (4,)} [1 2 3 4]
1 = {ndarray: (4,)} [0 1 2 3]

May I know where did I do wrong?

6
  • May you tell us where the occurs? (The traceback) Commented Jan 20, 2021 at 5:49
  • @hpaulj, I have edited the thread, but to answer your question the error occur at the last line lateral[mask!-0] Commented Jan 20, 2021 at 5:53
  • Tell us about lateral. You could even show the whole thing! Be generkus with the information. Good answers show results. Commented Jan 20, 2021 at 5:55
  • It is a 2D coordinate. and I would like to extract certain 2D coordinate if it fulfill the boolean condition. I hope this answer this your question @hpaulj Commented Jan 20, 2021 at 5:57
  • 1
    No. From the docs I see it is a tuple. We index a tuple with a simple number. a boolean array works on arrays, not tuples. Commented Jan 20, 2021 at 6:36

1 Answer 1

1

So it seems like the size of the mask and lateral[0] are different. Since mask is the difference between each element in the array, it is of size n-1 when lateral[0] is of size n. You might want to append to the mask array instead. Also, since lateral is a tuple, you would need to index on the tuple before applying the mask.

You might be need something like this:

import numpy as np
n_max = 5
list_no = np.arange(0, n_max)
lateral = np.tril_indices(n_max, -1)
mask = np.diff(lateral[0].astype(int))
mask = np.append(mask, 1)
expected_0 = lateral[0][mask != 0]
print(expected_0)
expected_1 = lateral[1][mask != 0]
print(expected_1)

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.