create a feature based on a condition for 3 possible outpus in python

You can create a feature based on a condition with three possible outputs in Python using a conditional statement. Here's an example using the NumPy library:

main.py
import numpy as np

# Sample data
data = np.array([1, 3, 5, 7, 9])

# Create a new feature based on a condition
new_feature = np.where(data < 5, 'Low', np.where(data < 8, 'Medium', 'High'))

print(new_feature)
210 chars
10 lines

In this example, we have a NumPy array data with values [1, 3, 5, 7, 9]. We create a new feature new_feature based on the following conditions:

  • If the value is less than 5, the feature is set to 'Low'.
  • If the value is less than 8, the feature is set to 'Medium'.
  • Otherwise, the feature is set to 'High'.

The output will be ['Low' 'Low' 'Medium' 'Medium' 'High'].

You can modify the conditions and the outputs according to your specific requirements.

gistlibby LogSnag