找到特定值并用其他值替换。python
我对编程很陌生。我有matlab中的代码:找到特定值并用其他值替换。python,python,arrays,matlab,for-loop,numpy,Python,Arrays,Matlab,For Loop,Numpy,我对编程很陌生。我有matlab中的代码: x2(x2>=0)=1; x2(x2<0)=-1; %Find values in x2 which are less than 0 and replace them with -1, %where x2 is an array like 0,000266987932788242 0,000106735120804439 -0,000133516844874253 -0,000534018243439120 我试图用Python代
x2(x2>=0)=1;
x2(x2<0)=-1;
%Find values in x2 which are less than 0 and replace them with -1,
%where x2 is an array like
0,000266987932788242
0,000106735120804439
-0,000133516844874253
-0,000534018243439120
我试图用Python代码来实现这一点
if x2>=0:
x2=1
if x2<0:
x2=-1
这将返回ValueError:包含多个元素的数组的真值不明确。使用a.any或a.all
我应该怎样做才能将所有的正片替换为1,负片替换为-1,并将所有这些存储在x2中,例如,不只是打印,以便以后我可以使用它来做其他事情。首先:
x2 = [0.000266987932788242, 0.000106735120804439, -0.000133516844874253, -0.000534018243439120]
print [1 if num >= 0 else num for num in x2]
输出
第二:
x2 = [-1, 2, -3, 4]
print [-1 if num < 0 else num for num in x2]
如果您需要在一个语句中同时使用这两个
您可以使用numpy在布尔数组上建立索引的功能
import numpy as np
x = np.array([-5.3, -0.4, 0.6, 5.4, 0.0])
not_neg = x >= 0 # creates a boolean array
x[not_neg] = 1 # index over boolean array
x[~not_neg] = -1
结果:
>>> x
array([-1., -1., 1., 1., 1.])
现在更新我的答案。请检查。最后一行可以是x[~非负]=-1。
x2 = [0.000266987932788242, 0.000106735120804439, -0.000133516844874253, -0.000534018243439120]
x2 = [-1 if num < 0 else 1 for num in x2]
print x2
[1, 1, -1, -1]
import numpy as np
x = np.array([-5.3, -0.4, 0.6, 5.4, 0.0])
not_neg = x >= 0 # creates a boolean array
x[not_neg] = 1 # index over boolean array
x[~not_neg] = -1
>>> x
array([-1., -1., 1., 1., 1.])