[파이썬][numpy] numpy `where` 함수

In this blog post, we will delve into the numpy where function in Python and demonstrate its usefulness in array manipulation and conditional operations.

Introduction to numpy where

The numpy where function is a powerful tool in the numpy library that allows us to perform element-wise conditional operations on arrays. It provides a flexible and efficient way to substitute or alter values based on specific conditions.

Syntax

The syntax for the numpy where function is as follows:

numpy.where(condition, x, y)

Example Usage

Let’s look at some code examples to understand how the numpy where function works:

  1. Simple Conditional Operation:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 3, 'Yes', 'No')

print(result)

Output:

['No' 'No' 'No' 'Yes' 'Yes']

In this example, we are using numpy where to determine if each element in the array arr is greater than 3. If it is, we get the string ‘Yes’, otherwise ‘No’.

  1. Array Manipulation:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 2, arr*2, arr)

print(result)

Output:

[ 1  2  6  8 10]

In this example, we use numpy where to double the values in arr that are greater than 2. The elements less than or equal to 2 remain unchanged.

Conclusion

The numpy where function is a handy tool for performing conditional operations on arrays in Python. It enables us to easily substitute or alter values based on specific conditions. By leveraging this function, you can efficiently manipulate arrays and streamline your code.