Python - NumPy 'where' function multiple conditions

Learn about the Python NumPy 'where' function multiple conditions with examples. By Pranit Sharma Last updated : September 27, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose, we have a DataFrame df, and we have two columns percentage and division, if the percentage is > 60, the division is first. If 60 >=percentage>50, division is second and division is third if 50>=percentage>40.

NumPy 'where' function multiple conditions

We are going to use np.where() condition and we will try to tackle the problem of filtering on the basis of two conditions only but not the third one.

We use the np.where() function to select elements from a NumPy array, based on a condition. It returns the indices of elements in an input array where the given condition is satisfied.

For this purpose, we will first create a DataFrame with one column called percentage with its respective values. We will then make a new column by traversing all the percentages and giving them their corresponding divisions according to the condition.

To tackle the problem of comparing two conditions only, we check the value with np.where() condition to check all the three conditions and assign the values to them.

Let us understand with the help of an example,

Python program to demonstrate NumPy 'where' function multiple conditions

# Importing pandas package
import pandas as pd

# Import numpy package
import numpy as np

# Creating a Dictionary
d = {'Percentage':[45,56,78,98,76,88,76,43,54,67,54,77,67,98,59]}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display Original DataFrame
print("Created DataFrame 1:\n",df,"\n")

# checking the values
# create an empty list
l = []
for i in df['Percentage']:
    if i>60:
        l.append('First')
    elif i<=60 and i>50:
        l.append('Second')
    elif i<=50 and i>40:
        l.append('Third')

# Assign the list to a new column of DataFrame
df['Division'] = l

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: NumPy 'where' function multiple conditions

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.