【问题标题】:Conditional matrix operation in pythonpython中的条件矩阵运算
【发布时间】:2016-01-16 08:35:21
【问题描述】:

x 是一个从 0 到 1 的 n 个值的列表,用 linepace 创建。 y=x^3。如何创建一个条件函数,使 x

import numpy as np
n=100
x = np.linspace(0, 1, n)
y = np.power(x,3) 
# for all values where x<0.5: y=0.01

【问题讨论】:

    标签: python function matrix conditional


    【解决方案1】:

    你可以很容易地做到这一点:

    y[x<0.5] = 0.01
    

    样本输出:

    In [1]: import numpy as np
    
    In [2]: n=10
    
    In [3]: x = np.linspace(0, 1, n)
    
    In [4]: y = np.power(x,3)
    
    In [5]: x
    Out[5]:
    array([ 0.        ,  0.11111111,  0.22222222,  0.33333333,  0.44444444,
            0.55555556,  0.66666667,  0.77777778,  0.88888889,  1.        ])
    
    In [6]: y
    Out[6]:
    array([ 0.        ,  0.00137174,  0.01097394,  0.03703704,  0.0877915 ,
            0.17146776,  0.2962963 ,  0.47050754,  0.70233196,  1.        ])
    
    In [7]: y[x<0.5] = 0.01
    
    In [8]: y
    Out[8]:
    array([ 0.01      ,  0.01      ,  0.01      ,  0.01      ,  0.01      ,
            0.17146776,  0.2962963 ,  0.47050754,  0.70233196,  1.        ])
    

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多