0

I stumbled upon this post asking how to create a new numpy matrix based upon a simple logical expression

For instance

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])

But I would like to use a more complex logical function, for example I would like to create a categorical, one-hot encoded variable, like so

X_Slow = (Y < 500).astype(int)
X_Medium = (Y >= 500 and Y < 1000).astype(int)
X_Fast = (Y >= 1000).astype(int)

But obviously the above manipulation is incorrect syntactically. I have tried

X_Medium = (Y[np.logical_and(Y >= 500,Y < 1000)]).astype(int)

Though this only returns an array with the number of elements that match the given criteria, I would like both "1s and 0s" in the column.

How can I do this in numpy?

KDecker
  • 6,928
  • 8
  • 40
  • 81

1 Answers1

0

Try X_Medium = np.logical_and(Y >= 500, Y < 1000).astype(int) instead

Optixal
  • 108
  • 1
  • 9