Performing a certain operation on arrays in Python

Question:

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]]])
Asked By: user20032724

||

Answers:

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.

Answered By: Hardy Wen

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]]
Answered By: airalcorn2
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.