Python 将NumPy数组的指定元素转换为新值
我想将NumPy数组A:1、5和8的指定元素转换为0 因此,我做了以下工作:Python 将NumPy数组的指定元素转换为新值,python,arrays,numpy,Python,Arrays,Numpy,我想将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 >>> B[np.in1d(B, bads).reshape(3, 3)] = 0 >>> B array([[0, 0, 2],
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
>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
[3, 4, 0],
[6, 7, 0]])
是的,我得到了预期的结果,即新的数组
然而,在我的实际问题中,给定的数组A非常大,也是二维的,要转换为0的坏_值的数量也太多了。因此,我尝试了以下方法:
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中坏值出现位置的索引,可以使用INAD找出哪些值是坏值: 因此,您可以只编写一个[np.inada,bads]=0,将A的坏值设置为0 编辑:如果阵列是二维的,一种方法是使用一维方法,然后重塑形状:
>>> 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)
因此,您可以执行以下操作:
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
>>> B[np.in1d(B, bads).reshape(3, 3)] = 0
>>> B
array([[0, 0, 2],
[3, 4, 0],
[6, 7, 0]])
谢谢对不起,我忘了提到我的真实数组A是二维的。你的解决方案还可以吗?非常感谢。认可的。如果我的分数超过15分,我会投票。没问题!很高兴你发现这个答案很有用。