Home > Backend Development > Python Tutorial > How to Use NumPy \'where\' with Multiple Conditions?

How to Use NumPy \'where\' with Multiple Conditions?

Susan Sarandon
Release: 2024-10-19 12:59:29
Original
745 people have browsed it

How to Use NumPy

Numpy "where" with Multiple Conditions

In the context of data analysis, it is often necessary to define custom conditions and assign accordingly different values based on those conditions. Numpy's "where" function can be used to handle such scenarios. However, challenges arise when dealing with multiple conditions.

A specific case is trying to add a new column "energy_class" to a dataframe "df_energy." The "energy_class" values are assigned based on the following conditions:

  • "high" if the "consumption_energy" value is greater than 400
  • "medium" if the "consumption_energy" value is between 200 and 400
  • "low" if the "consumption_energy" value is less than 200

The issue encountered was that the np.where function typically only supports two conditions.

To address this, numpy's "select" function can be employed. Here's an example:

<code class="python">col         = 'consumption_energy'
conditions  = [ df2[col] >= 400, (df2[col] < 400) & (df2[col]> 200), df2[col] <= 200 ]
choices     = [ "high", 'medium', 'low' ]
    
df2["energy_class"] = np.select(conditions, choices, default=np.nan)</code>
Copy after login

This code snippet uses "np.select" to evaluate multiple conditions and assign values from the corresponding "choices" list. The "default" parameter is used to handle any cases that do not meet the specified conditions.

The above is the detailed content of How to Use NumPy 'where' with Multiple Conditions?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template