[英]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使所有值 < 4 变为零
I do NOT want this, however.但是,我不想要这个。
Want I want to know is how to turn, say, entries 0, 5, 8, 9 into zero.我想知道的是如何将条目 0、5、8、9 变成零。
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 给出
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.顺便说一句,我正在使用 python。
Thank you谢谢
As you labeled your question numpy I assume you want to work with numpy arrays?正如您标记您的问题 numpy 我假设您想使用 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创建 arrays 和 output 它们,这样你就可以有一个前后
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:这将遍历 M 中的所有值并将 Y 中的位置设置为零:
for pos in M:
Y[pos] = 0
Output new array to show difference: Output 新数组显示差异:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.