简体   繁体   中英

how to replace negative and positive values in a matrix with a value deriving from a formula

I have this type of matrix (simulated floating rates)

在此处输入图片说明

I want to compute the payoff of the floating leg but I would like to return a matrix in which: - when the value is negative, the payoff is computed using a formula (in which the rate in that point is applied) - when the value is positive, the payoff is computed using another formula (in which the rate in that point is applied)

I was able to compute a matrix by applying only one formula but I cannot get the result that I want to achieve by applying IF Condition.

Any suggestion is appreciated! Thank you

Stef

Use masks:

matrix = [...]
result = numpy.zeros_like(matrix)
mask = matrix < 0
result[mask] = formula_A(matrix[mask])
mask = matrix > 0
result[mask] = formula_B(matrix[mask])

You can use np.where . In the example below, foo is applied where the matrix is positive, and bar is applied where the matrix is negative.

def foo(m):
    return m + 10
def bar(m):
    return m - 10
np.random.seed(0)
m = np.random.randn(3, 3)
>>> m
array([[ 1.76405235,  0.40015721,  0.97873798],
       [ 2.2408932 ,  1.86755799, -0.97727788],
       [ 0.95008842, -0.15135721, -0.10321885]])

>>> np.where(m > 0, foo(m), bar(m))
array([[ 11.76405235,  10.40015721,  10.97873798],
       [ 12.2408932 ,  11.86755799, -10.97727788],
       [ 10.95008842, -10.15135721, -10.10321885]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM