0

I have a 1D numpy array of specific values:

array_1 = [1.0, 3.0, 7.0, 9.0, 6.0]

These values can be found in a second 1D numpy array, at varying indices:

array_2 = [0.0, 1.0, 12.0, 16.0, 3.0, 7.0, 25.0, 9.0, 1.0, 4.0, 6.0]

I want to pull values from a third 1D numpy array, the same size as array_2, based on the location of the values given in array_1 in array_2:

array_3 = [123.6, 423.4, 12.4, 14.5, 25.6, 67.8, 423.5, 52.3, 32.4, 87.9, 78.1]

So, in the example above, because the values of array_1 are found in the following places in array_2: [0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1]

I therefore want to pull the values in those same indices from array_3. In other words, I want to be left with the following array_4:

array_4 = [423.4, 25.6, 67.8, 52.3, 78.1]

What's the best way to go about doing this?

1
  • Value 1.0 appears twice in array_2. Is it intentional? Commented Jul 17, 2020 at 20:06

4 Answers 4

2

You can try np.intersect1d:

_,_,idx = np.intersect1d(array_1, array_2, return_indices=True)
out = np.array(array_3)[sorted(idx)]

Output out:

array([423.4,  25.6,  67.8,  52.3,  78.1])
Sign up to request clarification or add additional context in comments.

Comments

1

A non numpy way is

array_4 = []
for i in range(len(array_2)):
    if array_2[i] in array_1:
        array_4.append(array_3[i])
print(array_4)

Comments

0

Here is another way to do it:

indexes = np.where(array_2 == array_1[:,np.newaxis])

array_4 = array_3[indexes[1]]
print(array_4)

result:

[423.4  32.4  25.6  67.8  52.3  78.1]

Comments

0

Using np.unique

unq,idx,inv = np.unique(np.concatenate([array_2,array_1]),return_index=True,return_inverse=True)
poss = idx[inv[len(array_2):]]
np.array(array_3)[poss]
# array([423.4,  25.6,  67.8,  52.3,  78.1])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.