Search code examples
pythonsympy

sympy.Piecewise with numpy array


I'd like to implement sympy.Piecewise on numpy arrays.

Consider:

import numpy as np
from sympy import Piecewise

x = np.array([0.1,1,2])
y = np.array([10,10,10])
Piecewise((x * y, x > 0.9),(0, True))

However, when I tried running it I got the following error:

TypeError: Argument must be a Basic object, not ndarray

Is there a way to get around this?

I've tried list comprehension. However, it gets more difficult when there are more variables involved.


Solution

  • The simpy.Piecewise is not directly compatible with numpy arrays. Use np.where to achieve similar functionality:

    import numpy as np
    x = np.array([0.1,1,2])
    y = np.array([10,10,10])
    result = np.where(x > 0.9, x * y, 0)