Python NumPy where with examples

In this Python NumPy tutorial, we will discuss Python NumPy where and also we will cover the below examples:

  • Python NumPy where multiple conditions
  • Python NumPy where examples
  • Python NumPy where index
  • Python NumPy where dataframe
  • Python NumPy where nan
  • Python NumPy where return index
  • Python NumPy where or
  • Python NumPy where and
  • Python NumPy where in list

Python NumPy where

  • In this section, we will learn about Python NumPy where.
  • Python NumPy module provides a function where to convert NumPy array to another NumPy array.
  • Based on the condition of the NumPy array and the values of the two different sequences.
  • It’s a conditional expression that returns a NumPy array of boolean. In other two arguments are X and Y these are optional parameters. These can be an array-like structure.
  • If X and Y both are passed in NumPy where then it returns the element selected from X and Y based on the condition on the original array.
  • So if both X and Y parameters are passed then it returns a new NumPy array by selecting items X and Y based on the result for applying condition on the original NumPy array.
  • If X and Y arguments are not passed then only condition argument is passed then it returns the indexes of the elements that are true in the boolean NumPy array returns by the condition.

Syntax:

Here is the Syntax of Python numpy where:

numpy.where
           (
            condition
            [
            x,
            y
            ]
            )
  • It consists of three arguments
    • Condition: array_like,boolean
    • x,y: Values from which to choose. x, y and condition need to be in some shape.
    • out: ndarray (An array with elements from x where the condition is True, and elements from y elsewhere.

Example:

  • Suppose we have a numpy array and two list-objects.
  • Now we want to convert this numpy array to another array of the same size where it will contain the value from the given list.
  • LIke from a value in an array is greater than 5 then it should be replaced at high and if it’s less than 5 or equal to 5 then it should be replaced at low.

Let’s take an example to check how to use where function in numpy.

import numpy as np

arr= np.array([4,5,6,7])
x = ['High','High','High','High']
y = ['Low','Low','Low','Low']
new_arr = np.where(arr > 5,x,y)
print(new_arr)

Here is the Screenshot of following given code

Python numpy where
Python numpy where

Read: Python NumPy Random

Python NumPy where multiple conditions

  • In this section, we will learn about Python NumPy where multiple conditions.
  • Using numpy.where() method on a NumPy array with multiple conditions returns the indices of the array for which each condition is true.
  • In this method, we use logical operators to use numpy.where() with multiple conditions
  • The logical AND has been used to define the condition. The first where() function has applied in a one-dimensional array that will return the array of indices of the input array where the condition will return true.

Syntax:

Here is the Syntax of Python numpy where

numpy.where
           (
            condition
            [
            x,
            y
            ]
            )

Example:

Suppose we have a numpy array. Now let’s see how to pass multiple conditions in the where function. Now there are some important points to remember the size of the list which we are passing second and the third argument should always equal to the size of the numpy array.

import numpy as np

arr= np.array([10,14,17,18])
x = ['High','High','High','High']
y = ['Low','Low','Low','Low']
new_arr = np.where((arr > 10) & (arr >14),x,y)
print(new_arr)

Here is the Screenshot of following given code

Python numpy where multiple condition
Python numpy where multiple condition

Here, we saw an example of NumPy where multiple conditions in Python.

Read: Check if NumPy Array is Empty in Python

Python numpy where examples

  • In this section, we will learn about Python NumPy where() examples.
  • In this method, we will look at the various ways the NumPy where the function can be used for a variety of use cases.
  • First, we take an example to replace elements with numpy.where() function. we will use a 2d random array and only output the positive elements.
  • The second example is using numpy.where() with only one condition.
  • The third example is broadcasting with numpy.where(). If we provide all of condition x and y arrays, NumPy will broadcast them together.

Syntax:

Here is the Syntax of Python numpy where

numpy.where
           (
            condition
            [
            x,
            y
            ]
            )

Example:

import numpy as np

a = np.array([1,2,5,6,7])
b = np.where(a > 0, a, 0)
print(b)
 
a = np.array([2,6,7,8])
b = np.where(a > 0) #only one condition
print(b)

a = np.array([2,5,7,8,9])
b = np.array([4,5,6,8,9])
c = np.where(a < 5, a, b * 10) #broadcasting with numpy 
print(c)

Here is the Screenshot of following given code

Python numpy where examples
Python numpy where examples

Read: Python NumPy zeros + Examples

Python NumPy where the index

  • In this section, we will learn about Python NumPy where() index.
  • In this method, we will discuss how to find an index of a value in a NumPy array using numpy.where().
  • Array indexing refers to any use of the square brackets to index array values.
  • First, we have to create a numpy array and search the elements and get the index of the element with a value of 4.

Syntax:

Here is the Syntax of Python numpy where

numpy.where
           (
            condition
            [
            x,
            y
            ]
            )

Example:

import numpy as np

arr = np.array([4,5,6,7,8,9,4])
res = np.where(arr == 4)
print(res)

Here is the Screenshot of following given code

Python numpy where the index
Python numpy where the index

Read: Python NumPy Sum + Examples

Python numpy where dataframe

  • In this section, we will learn about Python NumPy where() dataframe.
  • First, we have to create a dataframe with random numbers 0 and 100.
  • For each element in the calling Data frame, if the condition is true the element is used otherwise the corresponding element from the dataframe other is used.

Syntax:

Here is the Syntax of where dataframe

Dataframe.where
               (
                cond,
                other=nan.
                axis=None,
                level=None,
                try_cast=false
               )
  • It consists of few parameters.
    • Condition: Where cond is True, keep the original value. Where False, replace with the corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array.
    • Other: Scaler, Series/Dataframe, or cappable.
    • Axis: Alignment axis if needed.
    • level: alignment level if needed.

Example:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(8).reshape(-1, 2), columns=['C', 'D'])
n = df % 2 == 0
k = df.where(n, -df)
print(k)

Here is the Screenshot of following given code

Python numpy where dataframe
Python numpy where dataframe

Read: Python NumPy arange

Python NumPy where nan

  • In this section, we will learn about Python numpy where() nan.
  • In this method, we will combine both functions np.isnan and np.where() for replacing a nan value.
  • Nan standing for not a number is a numeric datatype value.
  • You can use np. where to match the boolean condition corresponding to nan values of the array and map each outcome to generate a list of tuples.

Example:

import numpy as np
x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))
y = list(map(tuple, np.where(np.isnan(x))))
print(y)

Here is the Screenshot of following given code

Python numpy where nan
Python numpy where nan

Python numpy where return index

  • In this section, we will learn about Python numpy where() return index.
  • In this method, we will discuss how to return an index of a value in a NumPy array using numpy. where().
  • First, we have to create a NumPy array and search the elements and get the index of the element with a value of 7.
  • The result is a tuple of arrays (one for each axis) containing the indices where value 7 exists in array arr.

Syntax:

Here is the Syntax of Python numpy where

numpy.where
           (
            condition
            [
            x,
            y
            ]
            )

Example:

import numpy as np

arr = np.array([4,5,6,7,8,9,4])
res = np.where(arr == 7)
print(res)

Here is the Screenshot of following given code

Python numpy where return index
Python numpy where return index

Read: Python NumPy append + 9 Examples

Python numpy where or

  • In this section, we will learn about Python NumPy where() OR.
  • The logical OR operator compute the truth value of arr1 or arr2 element-wise.
  • It will return the boolean result of the logical OR operation applied to the elements of arr1 and arr2.

Syntax:

numpy.logical_or
               (
                arr1,
                arr2,
                out=None,
                where=True,
                casting='same_kind',
                dtype=None
               )

Example:

import numpy as np

x = np.array([1,2,3,4,5])
y = np.logical_or(x < 1, x > 3)
print(y)

Here is the Screenshot of following given code

Python numpy where or
Python numpy where or

Python numpy where and

  • In this section, we will learn about Python numpy where() and.
  • In this method, we use logical operators to use numpy.where() with multiple conditions
  • The logical AND has been used to define the condition. The first where() function has applied in a one-dimensional array that will return the array of indices of the input array where the condition will return true.

Example:

import numpy as np

arr= np.array([10,14,17,18])
x = ['High','High','High','High']
y = ['Low','Low','Low','Low']
new_arr = np.where((arr > 10) & (arr >14),x,y)
print(new_arr)

Here is the Screenshot of following given code

Python numpy where And
Python numpy where And

Read: Python NumPy where

Python numpy where in list

  • In this section, we will learn about Python NumPy where() in list.
  • First, we create a list and use the function numpy.where().
  • In this example, a Python list and a Numpy array will be created. The size of each element and then the whole size of both the containers will be calculated and comparison will be done

Example:

import numpy as np

a = np.array([1,2,5,6,7])
b = np.where(a > 0, a, 0)
print(b)

Here is the Screenshot of following given code

Python numpy where in list
Python numpy where in list

You may like the following Python tutorials:

In this Python tutorial, we discussed Python NumPy where and also we will cover the below examples:

  • Python NumPy where multiple conditions
  • Python NumPy where examples
  • Python NumPy where index
  • Python NumPy where dataframe
  • Python NumPy where nan
  • Python NumPy where return index
  • Python NumPy where or
  • Python NumPy where and
  • Python NumPy where in list