0

I need to slice an array of xyz coordinates based on conditions in a boolean array (where the boolean array is 1D).

If my boolean array is

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

I need it to slice it to produce the following index arrays:

[0, 1, 2, 3, 6, 7, 10, 11, 12] ([:-2] between True indices)

The ultimate desired output would be an array of the xyz coordinates at those indices:

[xyz[0], xyz[1], xyz[2] xyz[3], xyz[6] xyz[7], xyz[10] xyz[11], xyz[12]]

The other two slices (with similar desired outputs) are as follows:

[1, 2, 3, 4, 7, 8, 11, 12, 13] ([1:-1] between True indices)

[2, 3, 4, 5, 8, 9, 12, 13, 14] ([2:] between True indices)

Is there a pythonic way to do this without a list comprehension?

Thank you!

Community
  • 1
  • 1
stagermane
  • 1,003
  • 2
  • 12
  • 29
  • What should be a result of this "slice", e.g. what output is expected for `[0, 1, 2, 3, 6, 7, 10, 11, 12] ([:-2] between True indices)`? – Vader Oct 24 '16 at 09:15
  • The indices are the output (I think). The ultimate goal is to isolate the xyz coordinates of interest at those indices. I will edit the question for clarity – stagermane Oct 24 '16 at 09:19
  • Why without list comprehension? This is probably the most pythonic way – Chris_Rands Oct 24 '16 at 09:30
  • I'm trying to vectorize a large portion of code, so I'm trying to avoid list comprehensions where possible and rely on mapping as much as possible. Some of the list comprehensions are unavoidable, I just wanted to know if in this case, there is a better way. – stagermane Oct 24 '16 at 09:35

1 Answers1

1

It looks like numpy.ndarray.nonzero is what you need:

a = np.asarray([1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1])
print(a.nonzero())

Outputs:

array([ 0,  5,  6,  9, 10, 14])
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271