Question
Question

Reputation: 15

how to overwrite only a portion of the array?

i have an array that contains labels, for instance

    X1 = [1, 0, 1, 2, 3, 1, 3, 2, 3, 1, 0]
    X1 = np.array(X1)

I also have an array X2 that contains the updated labels for label [1] in X1, for instance.

    X2 = [-1, 1, -1, -1]
    X2 = np.array(X2)

how to overwrite X1 for all labels equal to [1] to be X2? The output should look like:

    New_X1 = [-1, 0, 1, 2, 3, -1, 3, 2, 3, -1, 0]

I tried something like this:

    New_X1 = [np.where(X1==1)]= X2

This obviously didn't work. Any help, please.

Upvotes: 0

Views: 76

Answers (3)

Question
Question

Reputation: 15

Thank you all for your feedback. All correct. Here is what i did, based on your feedback.

    New_X1 = X1.copy()
    New_X1[X1 == 1] = X2

Upvotes: 0

Max Shouman
Max Shouman

Reputation: 1331

Here's a nice and concise way to accomplish your task through map():

New_X1 = list(map(lambda x1: x1 if x1 != 1 else X2.pop(0), X1))

EDIT: I've seen you edited your post specifying that the sequences are np arrays: you can easily adapt this implementation to that case too.

Upvotes: 1

rayryeng
rayryeng

Reputation: 104565

Assuming that the lists you've written down are indeed NumPy arrays, you are not indexing into New_X1 properly. It should be:

New_X1[np.where(X1 == 1)] = X2

However, you can achieve the same thing with logical indexing instead. It's not only cleaner, but faster:

New_X1[X1 == 1] = X2

Upvotes: 1

Related Questions