pythonpandasnumpydataframe

Numpy "where" with multiple conditions


I try to add a new column "energy_class" to a dataframe "df_energy" which contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see that numpy.where(condition[, x, y]) treat only two condition not 3 like in my case.


Solution

  • You can use a ternary:

    np.where(consumption_energy > 400, 'high', 
             (np.where(consumption_energy < 200, 'low', 'medium')))