0

I have two arrays I and X. I want to perform an operation which basically takes the indices from I and uses values from X. For example, I[0]=[0,1], I want to calculate X[0] and X[1] followed by X[0]-X[1] and append to a new array T. Similarly, for I[1]=[1,2], I want to calculate X[1] and X[2] followed by X[1]-X[2] and append to T. The expected output is presented.

import numpy as np
I=np.array([[0,1],[1,2]])
X=np.array([10,5,3])

The expected output is

T=array([[X[0]-X[1]],[X[1]-X[2]]])

2 Answers 2

1

The most basic approach is using nested indices together with the np.append() function.

It works like below:

T = np.append(X[I[0][0]] - X[I[0][1]], X[I[1][0]] - X[I[1][1]])

Where, X[I[0][0]] means to extract the value of I[0][0] and use that as the index we want for the array X.

You can also implement a loop to do that:

T = np.array([], dtype="int64")
for i in range(I.shape[0]):
    for j in range(I.shape[1]-1):
        T = np.append(T, X[I[i][j]] - X[I[i][j+1]])

If you find this answer helpful, please accept my answer. Thanks.

Sign up to request clarification or add additional context in comments.

3 Comments

How will the answer change if X=np.array([[10,5,3]]) instead of X=np.array([10,5,3])?
If so, you need to change the last line of the loop to T = np.append(T, X[0, I[i][j]] - X[0, I[i][j+1]])
For large arrays, using for loops like this is going to be much slower than using vectorized operations like what's shown in my answer --> stackoverflow.com/a/74761269/1316276.
1

You can do this using integer array indexing. For large arrays, using for loops like in the currently accepted answer is going to be much slower than using vectorized operations.

import numpy as np

I = np.array([[0, 1], [1, 2]])
X = np.array([10, 5, 3])
T = X[I[:, 0:1]] - X[I[:, 1:2]]

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.