[英]How do I replace certain elements of an array with 0?
我見過很多人用基於值的零替換數組的某些元素的例子。
例子:
Y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]
使所有值 < 4 變為零
但是,我不想要這個。
我想知道的是如何將條目 0、5、8、9 變成零。
例子:
Y = [0.5, 18, -6, 0.3, 1, 0, 0, -1, 10, -0.2, 20]
並且我想變成零的條目由數組 M 給出
M = [0, 5, 8, 9]
所以我最終得到
Y = [0, 18, -6, 0.3, 1, 0, 0, -1, 0, 0, 20]
順便說一句,我正在使用 python。
謝謝
正如您標記您的問題 numpy 我假設您想使用 numpy arrays? 如果是這樣,您可以這樣做:
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
代碼
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)
解釋:
創建 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)
這將遍歷 M 中的所有值並將 Y 中的位置設置為零:
for pos in M:
Y[pos] = 0
Output 新數組顯示差異:
print("new: ", end="")
print(Y)
您可以遍歷第二個數組來編輯第一個數組。
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]
簡單的方法
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.