Carlos Eduardo Corpus
Carlos Eduardo Corpus

Reputation: 349

Replacing the values of a numpy array of zeros using a array of indexes

I'm working with numpy and I got a problem with index, I have a numpy array of zeros, and a 2D array of indexes, what I need is to use this indexes to change the values of the array of zeros by the value of 1, I tried something, but it's not working, here is what I tried.

import numpy as np

idx = np.array([0, 3, 4], 
               [1, 3, 5],
               [0, 4, 5]]) #Array of index

zeros = np.zeros(6) #Array of zeros [0, 0, 0, 0, 0, 0]

repeat = np.tile(zeros, (idx.shape[0], 1)) #This repeats the array of zeros to match the number of rows of the index array

res = []
for i, j in zip(repeat, idx):
        res.append(i[j] = 1) #Here I try to replace the matching index by the value of 1

output = np.array(res)

but I get the syntax error

expression cannot contain assignment, perhaps you meant "=="?

my desired output should be

output = [[1, 0, 0, 1, 1, 0],
          [0, 1, 0, 1, 0, 1],
          [1, 0, 0, 0, 1, 1]]

This is just an example, the idx array can be bigger, I think the problem is the indexing, and I believe there is a much simple way of doing this without repeating the array of zeros and using the zip function, but I can't figure it out, any help would be aprecciated, thank you!

EDIT: When I change the = by == I get a boolean array which I don't need, so I don't know what's happening there either.

Upvotes: 0

Views: 926

Answers (1)

Mark
Mark

Reputation: 92461

You can use np.put_along_axis to assign values into the array repeat based on indices in idx. This is more efficient than a loop (and easier).

import numpy as np

idx = np.array([[0, 3, 4], 
                [1, 3, 5],
                [0, 4, 5]]) #Array of index

zeros = np.zeros(6).astype(int) #Array of zeros [0, 0, 0, 0, 0, 0]
repeat = np.tile(zeros, (idx.shape[0], 1))

np.put_along_axis(repeat, idx, 1, 1)

repeat will then be:

array([[1, 0, 0, 1, 1, 0],
       [0, 1, 0, 1, 0, 1],
       [1, 0, 0, 0, 1, 1]])

FWIW, you can also make the array of zeros directly by passing in the shape:

np.zeros([idx.shape[0], 6])

Upvotes: 1

Related Questions