Carlos Eduardo Corpus
Carlos Eduardo Corpus

Reputation: 349

Adding values of a 1D array to a 2D array based on a 1D array of indexes

I'm working with numpy and I hit a roadblock, I think it's an easy question and can be done using indexing, but I still haven't figure it out. So I have 2D array and from each row I get the index of the minimum value, what I want is to use this index to add values to the 2D array, here is an example

a = np.array([[9, 4, 9, 9],
              [1, 6, 4, 6],
              [8, 7, 1, 5],
              [8, 9, 2, 7]])

values = np.array([1, 2, 3, 4])

minimum = np.argmin(a, axis = 1) #To find the index of the minimum values

print(minimum) #minimum = [1, 0, 2, 2]

So in the first row of the 2D array and the first index of the minimum array I want to add the value of 1, in the second row of the 2D array using the second index, I want to add the value of 2 and so on, my desired output should be something like this.

output = [[9, 5, 9, 9],
          [3, 6, 4, 6],
          [8, 7, 4, 5],
          [8, 9, 6, 7]]

I try this, but I failed:

newarray = a[:, minimum] + values

newarray = [[ 5, 11, 12, 13],
            [ 7,  3,  7,  8],
            [ 8, 10,  4,  5],
            [10, 10,  5,  6]]

Thank you for all your help!

Upvotes: 0

Views: 34

Answers (1)

Julien
Julien

Reputation: 15070

You were close. Try this:

newarray = a.copy()
newarray[np.arange(len(a)), minimum] += values

Upvotes: 1

Related Questions