Solveig
Solveig

Reputation: 55

How do I replace certain elements of an array with 0?

I have seen many examples of people replacing certain elements of an array with zero-based on value.

example:

Y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]

Making all values < 4 turns into zero

I do NOT want this, however.

Want I want to know is how to turn, say, entries 0, 5, 8, 9 into zero.

example:

Y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]

and the entries I want to turn into zero are given by the array M

M = [0, 5, 8, 9] 

so that I end up with

Y = [0, 18, -6, 0.3, 1, 0, 0, -1, 0, 0, 20]

I am working with python by the way.

Thank you

Upvotes: 0

Views: 1623

Answers (4)

Mont
Mont

Reputation: 194

Simple way 🤔


arr = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]
replace_idx = [0, 5, 8, 9]
out = [0 if idx in replace_arr else item for idx,item in  enumerate(arr)]


Upvotes: 0

Infinite Recursion
Infinite Recursion

Reputation: 161

Code

Y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]
M = [0, 5, 8, 9]
print("old: ", end="")
print(Y)

for pos in M:
    Y[pos] = 0

print("new: ", end="")
print(Y)

Explanation:

Create the arrays and output them so you can have a before and after

Y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]
M = [0, 5, 8, 9]
print("old: ", end="")
print(Y)

This iterates over all of the values in M and sets the positions in Y to zero:

for pos in M:
    Y[pos] = 0

Output new array to show difference:

print("new: ", end="")
print(Y)

Upvotes: 2

Allan J.
Allan J.

Reputation: 520

You can loop over the second array to edit the first one.

y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]

m = [0, 5, 8, 9]

for item in m:
    y[item] = 0

print(y) # prints [0, 18, -6, 0.3, 1, 0, 0, -1, 0, 0, 20]

Upvotes: 0

aramirezreyes
aramirezreyes

Reputation: 1365

As you labeled your question numpy I assume you want to work with numpy arrays? If so, you can do:

import numpy as np
Y = np.array([0, 18, -6, 0.3, 1, 0, 0, -1, 0, 0, 20])
M = np.array([0, 5, 8, 9])
Y[M] = 0

Upvotes: 2

Related Questions