Numpy 배열에서 요소를 이동하는 방법(예제 포함)


다음 방법 중 하나를 사용하여 NumPy 배열의 요소를 오프셋할 수 있습니다.

방법 1: 요소 이동(모든 원래 요소 유지)

 #shift each element two positions to the right
data_new = np. roll (data, 2)

방법 2: 요소 이동(요소 교체 허용)

 #define shifting function
def shift_elements (arr, num, fill_value):
    result = np. empty_like (arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else :
        result[:] = arr
    return result

#shift each element two positions to the right (replace shifted elements with zero)
data_new = shift_elements(data, 2, 0)

다음 예에서는 각 방법을 실제로 사용하는 방법을 보여줍니다.

방법 1: 요소 이동(모든 원래 요소 유지)

다음 코드는 np.roll() 함수를 사용하여 NumPy 배열의 각 요소를 오른쪽으로 두 위치 이동하는 방법을 보여줍니다.

 import numpy as np

#create NumPy array
data = np. array ([1, 2, 3, 4, 5, 6])

#shift each element two positions to the right
data_new = np. roll (data, 2)

#view new NumPy array
data_new

array([5, 6, 1, 2, 3, 4])

각 요소는 오른쪽으로 두 위치 이동되었으며 배열 끝에 있는 요소는 단순히 앞으로 이동되었습니다.

np.roll() 함수에서 음수를 사용하여 요소를 왼쪽으로 이동할 수도 있습니다.

 import numpy as np

#create NumPy array
data = np. array ([1, 2, 3, 4, 5, 6])

#shift each element three positions to the left
data_new = np. roll (data, -3)

#view new NumPy array
data_new

array([4, 5, 6, 1, 2, 3])

방법 2: 요소 이동(요소 교체 허용)

NumPy 배열의 요소를 이동하고 이동된 요소를 특정 값으로 대체하는 사용자 정의 함수를 정의할 수도 있습니다.

예를 들어 다음 함수를 정의하여 요소를 이동하고 이동된 모든 요소를 값 0으로 바꿀 수 있습니다.

 import numpy as np

#create NumPy array
data = np. array ([1, 2, 3, 4, 5, 6])

#define custom function to shift elements
def shift_elements (arr, num, fill_value):
    result = np. empty_like (arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else :
        result[:] = arr
    return result

#shift each element two positions to the right and replace shifted values with zero
data_new = shift_elements(data, 2, 0)

#view new NumPy array
data_new

array([0, 0, 1, 2, 3, 4])

함수에 음수를 사용하여 요소를 왼쪽으로 이동할 수도 있습니다.

 import numpy as np

#create NumPy array
data = np. array ([1, 2, 3, 4, 5, 6])

#define custom function to shift elements
def shift_elements (arr, num, fill_value):
    result = np. empty_like (arr)
    if num > 0:
        result[:num] = fill_value
        result[num:] = arr[:-num]
    elif num < 0:
        result[num:] = fill_value
        result[:num] = arr[-num:]
    else :
        result[:] = arr
    return result

#shift each element three positions to the left and replace shifted values with 50
data_new = shift_elements(data, -3, 50)

#view new NumPy array
data_new

array([ 4, 5, 6, 50, 50, 50])

추가 리소스

다음 튜토리얼에서는 NumPy에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

NumPy에서 요소 발생 횟수를 계산하는 방법
NumPy 배열을 열별로 정렬하는 방법
NumPy 배열의 모드를 계산하는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다