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

In this blog post, we will explore the array_equal function in the popular Python library, numpy.

Introduction to array_equal

The array_equal function in numpy is used to compare the equality of two NumPy arrays. It returns a boolean value indicating whether the arrays are equal or not.

The syntax of the array_equal function is as follows:

numpy.array_equal(arr1, arr2)

Here, arr1 and arr2 are the two arrays that you want to compare.

Examples

Let’s look at a few examples to understand how the array_equal function works.

Example 1: Equality of Arrays

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])

result = np.array_equal(arr1, arr2)
print(result)  # Output: True

In this example, we have two arrays arr1 and arr2, both containing the same elements. The array_equal function returns True because the arrays are equal.

Example 2: Inequality of Arrays

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

result = np.array_equal(arr1, arr2)
print(result)  # Output: False

In this example, the arrays arr1 and arr2 contain different elements. The array_equal function returns False because the arrays are not equal.

Example 3: Arrays with Different Shapes

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([[1, 2], [3, 4]])

result = np.array_equal(arr1, arr2)
print(result)  # Output: False

Here, arr1 is a 1-dimensional array, while arr2 is a 2-dimensional array. The array_equal function returns False because the arrays have different shapes and are not equal.

Conclusion

The array_equal function in the numpy library is a convenient tool for comparing the equality of NumPy arrays. It returns a boolean value indicating whether the arrays are equal or not. By using this function, you can easily perform array comparisons in your Python code.

I hope this blog post has helped you understand the array_equal function in numpy. Happy coding!