我想将 NumPy 数组 A
的指定元素:1、5 和 8 转换为 0。
所以我做了以下事情:
import numpy as np
A = np.array([[1,2,3,4,5],[6,7,8,9,10]])
bad_values = (A==1)|(A==5)|(A==8)
A[bad_values] = 0
print A
是的,我得到了预期的结果,即新数组。
然而,在我的现实世界问题中,给定的数组(A)非常大,而且也是二维的,并且要转换为 0 的 bad_values 的数量也太多。因此,我尝试了以下方法:
bads = [1,5,8] # Suppose they are the values to be converted into 0
bad_values = A == x for x in bads # HERE is the problem I am facing
我该怎么做?
那么,剩下的当然就和以前一样了。
A[bad_values] = 0
print A
最佳答案
如果您想获取数组A
中出现错误值的索引,您可以使用in1d
来找出bads中的值
:
>>> np.in1d(A, bads)
array([ True, False, False, False, True, False, False, True, False, False], dtype=bool)
因此,您只需编写 A[np.in1d(A, bads)] = 0
即可将 A
的坏值设置为 0
.
编辑:如果您的数组是二维的,一种方法是使用 in1d
方法,然后重新整形:
>>> B = np.arange(9).reshape(3, 3)
>>> B
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.in1d(B, bads).reshape(3, 3)
array([[False, True, False],
[False, False, True],
[False, False, True]], dtype=bool)
所以你可以执行以下操作:
>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
[3, 4, 0],
[6, 7, 0]])
关于python - 将 NumPy 数组的指定元素转换为新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084671/