繁体   English   中英

替换 numpy 数组中的值等于值列表

[英]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]

提前致谢!

如果imagefreq都是 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.

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