[英]Replace values in numpy array equal to list of values
我有一個 numpy 數組 - 具有各種值的圖像:示例圖像 = [1,2,2, 3, 4, 4, 4, 4, 5, 6, 6,7,8,8,8,8] 我想只替換那些出現少於兩次的數字 - 用一個特定的數字,比如說 0。我設法創建了這些數字的列表,如下所示:
(unique, counts) = np.unique(image, return_counts=True)
frequencies = np.asarray((unique, counts)).T
freq = frequencies[frequencies[:,1] < 2,0]
print(freq)
array([1, 3, 5, 7], dtype=int64)
如何用零替換這些數字?
結果應如下所示: [0,2,2, 0, 4, 4, 4, 4, 0, 6, 6,0,8,8,8,8]
提前致謝!
如果image
和freq
都是 numpy arrays:
freq = np.array([1, 3, 5, 7])
image = np.array([1 ,2 ,2, 3, 4, 4, 4, 4, 5, 6, 6 ,7 ,8 ,8 ,8 ,8])
解決方案 1
然后,您可以找到出現在freq
中的image
條目的索引,然后將它們設置為零:
image[np.argwhere(np.isin(image, freq)).ravel()] = 0
基於: 獲取 numpy 數組中項目的索引,其中值在 list 中。
解決方案 2
使用np.in1d
:
image = np.where(np.in1d(image,freq),0,image)
更多信息: Numpy - 檢查一個數組的元素是否屬於另一個數組
解決方案 3
您還可以使用列表推導:
image = [each if each not in freq else 0 for each in image]
可以在這里找到更多信息: if/else in a list comprehension 。
最后一個將產生一個列表,而不是 numpy 數組,但除此之外,所有這些都會產生相同的結果。
您可以將每個項目與數組的 rest 進行比較,以形成一個二維矩陣並對每個計數求和。 然后將滿足頻率條件的項目分配給期望的值:
import numpy as np
img = np.array([1 ,2 ,2, 3, 4, 4, 4, 4, 5, 6, 6 ,7 ,8 ,8 ,8 ,8])
img[np.sum(img==img[:,None],axis=1)<2] = 0
array([0, 2, 2, 0, 4, 4, 4, 4, 0, 6, 6, 0, 8, 8, 8, 8])
可能效率不高,但應該可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.