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

In this blog post, we will explore the take function in the Numpy library of Python. The take function allows us to extract elements from an array based on their indices. It provides a convenient way to access specific elements without using loops.

Syntax

The syntax of the take function is as follows:

numpy.take(arr, indices, axis=None, out=None, mode='raise')

Examples

Let’s look at some examples to understand how the take function works:

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3]

# Extract elements at indices 1 and 3
result = np.take(arr, indices)
print(result)  # Output: [20 40]

In the above example, we have an input array arr and a list of indices [1, 3]. By calling np.take(arr, indices), we extract the elements at indices 1 and 3 from the input array. The output is [20, 40].

We can also use the axis parameter to apply the indices along a specific axis. Let’s consider a 2-dimensional array:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
indices = [0, 2]

# Extract elements at indices 0 and 2 along axis 0
result = np.take(arr, indices, axis=0)
print(result)  # Output: [[1 2 3] [7 8 9]]

In the above example, the take function is applied along axis 0, which corresponds to extracting elements from each row based on the provided indices. The output is [[1, 2, 3], [7, 8, 9]].

Conclusion

The take function in Numpy provides a convenient way to extract elements from an array based on indices. It is useful for selective access of elements without using loops. By understanding the syntax and examples discussed in this blog post, you can apply the take function effectively in your Python programs.