【问题标题】:Finding specific values and replacing them by others. Python找到特定的值并用其他值替换它们。 Python
【发布时间】:2013-11-06 06:44:58
【问题描述】:

我对编程很陌生。我在 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 中使用代码来做到这一点

if x2>=0:
   x2=1
if x2<0:
   x2=-1

这会返回ValueError:具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()

我应该怎么做才能让所有的正面都被 1 取代,而负面则被 -1 取代> 和 STORE 所有这些都在 x2 中,例如,不只是打印,以便我可以使用它稍后再做一些其他的事情。

【问题讨论】:

  • 现在更新了我的答案。请检查。

标签: python arrays matlab for-loop numpy


【解决方案1】:

第一:

x2 = [0.000266987932788242, 0.000106735120804439, -0.000133516844874253, -0.000534018243439120]
print [1 if num >= 0 else num for num in x2]

输出

[1, 1, -0.000133516844874253, -0.000534018243439120]

第二:

x2 = [-1, 2, -3, 4]
print [-1 if num < 0 else num for num in x2]

输出

[0.000266987932788242, 0.000106735120804439,  -1, -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]

【讨论】:

    【解决方案2】:

    您可以使用 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[~not_neg] = -1
    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 2020-05-23
    • 2015-07-16
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多