简体   繁体   中英

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

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

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)

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]

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)]


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM