-1

I would like to test every single element of "z", with the "if else" condition and return desired equation. My implementation is resulting with an error. I tried "z.all" and "z.any" functions but these two are converting "z" to a boolean array. I do not want z as boolean array. How can I do this, while z remain as a numpy array?

z is a numpy array and its shape is (10610, ))

    def function(z):
        alpha = 1
        if (z < 0):
            return -alpha * z
        elif (0 <= z <= 1):
            return (3 * z ** 3) - (4 * z ** 2) + (2 * z)
        else:
            return z
James
  • 32,991
  • 4
  • 47
  • 70
  • Can you elaborate on why the methods `any` and `all` are not acceptable? – Brian61354270 Mar 19 '20 at 22:17
  • @Brian Z is storing numbers to use later. I would like to feed each element into if-else individually. When I use `any` or `all` it turns out each elements to a '1' or '0'. Isn't it? – Erdem Uysal Mar 19 '20 at 22:27
  • _is resulting with an error_ What error? **Please provide the entire error message, as well as a [mcve].** – AMC Mar 20 '20 at 02:26

3 Answers3

0

You can use numpy.where for the two conditions:

np.where(
    z < 0,
    -alpha * z,
    np.where(
        z <= 1,
        (3 * z ** 3) - (4 * z ** 2) + (2 * z),
        z))
a_guest
  • 34,165
  • 12
  • 64
  • 118
0

If I understand correctly you want to apply your function to all elements in the array z right? If so you might want to look into numpys vectorize function.

For your code:

vfunc = np.vectorize(function)
z = vfunc(z)

If speed and efficiency are important you can refer to this other answer where different methods are compared.

Rolo
  • 81
  • 2
  • 4
0

Using boolean indexing:

def function(z):
    alpha = 1

    m = (z < 0)
    z[m] = -alpha * z[m]

    m = ((z >= 0) & (z <= 1))
    z[m] = (3 * z[m] ** 3) - (4 * z[m] ** 2) + (2 * z[m])

    return z
berardig
  • 652
  • 4
  • 10