Reputation: 1
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
Upvotes: 0
Views: 110
Reputation: 109576
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]])
Upvotes: 0
Reputation: 42758
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])
Upvotes: 1