2

I have a first 3D numpy array and a second numpy array containing the locations (coordinates) of elements of the first I am interested in.

first = np.array([[[100, 101, 102],
                  [103, 104, 105],
                  [106, 107, 108]],

                 [[109, 110, 111],
                  [112, 113, 114],
                  [115, 116, 117]],

                 [[118, 119, 120],
                  [121, 122, 123],
                  [124, 125, 126]]])


second = np.array([[0, 1, 0],
                   [1, 1, 0],
                   [1, 0, 0],
                   [0, 0, 0],

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

result = np.array([103, 112, 109, 100, 104, 113, 110, 101])

The result I would like: all values located at the positions contained in the second array.

Using first[second] does not do the trick. I would like to avoid looping.

5
  • What about using np.where(second) to then perform an access to first from the result? Commented Nov 6, 2021 at 16:18
  • Thanks for your reply but I am not sure if I fully understand. first[np.where(second)] does not work either. Commented Nov 6, 2021 at 16:28
  • 1
    Show us first and what the expected output should be. "It does not work" is unacceptable. Commented Nov 6, 2021 at 16:36
  • What are the 0/1 values in second supposed to index? The relation of your 2d second to a unknown 3d is not clear. You may have to show "looping" code first to show us clearly what you are trying to do. Commented Nov 6, 2021 at 17:51
  • I updated the question using Mark's answer. I hope it is clearer now. Commented Nov 18, 2021 at 15:22

1 Answer 1

4

You can create a flat index array from your second array with numpy.ravel_multi_index(). This can then be passed to take() which will give you a flat list of values.

Given a starting array:

import numpy as np
m = np.arange(100, 127).reshape([3, 3, 3])

of

[[[100 101 102]
  [103 104 105]
  [106 107 108]]

 [[109 110 111]
  [112 113 114]
  [115 116 117]]

 [[118 119 120]
  [121 122 123]
  [124 125 126]]]

and your indexes:

second = np.array(
    [[0, 1, 0],
     [1, 1, 0],
     [1, 0, 0],
     [0, 0, 0],

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

i = np.ravel_multi_index(second.T, m.shape)
m.take(i)

results in:

array([103, 112, 109, 100, 104, 113, 110, 101])
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.