웹사이트 검색

Python에서 배열에 요소를 추가하는 방법


소개

Python에는 내장 배열 데이터 유형이 없지만 배열 작업에 사용할 수 있는 모듈이 있습니다. 이 문서에서는 배열 및 NumPy 모듈을 사용하여 배열에 추가하는 방법을 설명합니다. NumPy 모듈은 배열에서 수학 연산을 수행해야 할 때 유용합니다.

대부분의 경우 List는 혼합 데이터 유형과 같은 유연성을 제공하고 여전히 배열의 모든 특성을 가지고 있기 때문에 List를 사용하여 배열을 만들 수 있습니다. Python의 목록에 대해 자세히 알아보세요.

참고: 동일한 데이터 유형의 요소만 배열에 추가할 수 있습니다. 마찬가지로 동일한 데이터 유형의 두 배열만 조인할 수 있습니다.

Array 모듈을 사용하여 배열에 요소 추가

배열 모듈을 사용하면 + 연산자를 사용하여 배열을 연결하거나 결합할 수 있으며 append(), extend( )insert() 메서드.

Syntax Description
+ operator, x + y Returns a new array with the elements from two arrays.
append(x) Adds a single element to the end of the array.
extend(iterable) Adds a list, array, or other iterable to the end of array.
insert(i, x) Inserts an element before the given index of the array.

다음 예제에서는 두 배열을 결합하여 새 배열 객체를 만드는 방법을 보여줍니다.

import array

# create array objects, of type integer
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])

# print the arrays
print("arr1 is:", arr1) 
print("arr2 is:", arr2)

# create a new array that contains all of the elements of both arrays 
# and print the result
arr3 = arr1 + arr2
print("After arr3 = arr1 + arr2, arr3 is:", arr3)

출력은 다음과 같습니다.

Output
arr1 is: array('i', [1, 2, 3]) arr2 is: array('i', [4, 5, 6]) After arr3 = arr1 + arr2, arr3 is: array('i', [1, 2, 3, 4, 5, 6])

앞의 예제에서는 지정된 배열의 모든 요소를 포함하는 새 배열을 만듭니다.

다음 예제는 append(), extend()insert() 메서드를 사용하여 배열에 추가하는 방법을 보여줍니다.

import array

# create array objects, of type integer
arr1 = array.array('i', [1, 2, 3])
arr2 = array.array('i', [4, 5, 6])

# print the arrays
print("arr1 is:", arr1) 
print("arr2 is:", arr2)

# append an integer to an array and print the result
arr1.append(4)
print("\nAfter arr1.append(4), arr1 is:", arr1)

# extend an array by appending another array of the same type 
# and print the result
arr1.extend(arr2)
print("\nAfter arr1.extend(arr2), arr1 is:", arr1)

# insert an integer before index position 0 and print the result
arr1.insert(0, 10)
print("\nAfter arr1.insert(0, 10), arr1 is:", arr1)

출력은 다음과 같습니다.

Output
arr1 is: array('i', [1, 2, 3]) arr2 is: array('i', [4, 5, 6]) After arr1.append(4), arr1 is: array('i', [1, 2, 3, 4]) After arr1.extend(arr2), arr1 is: array('i', [1, 2, 3, 4, 4, 5, 6]) After arr1.insert(0, 10), arr1 is: array('i', [10, 1, 2, 3, 4, 4, 5, 6])

앞의 예제에서 각 메서드는 arr1 배열 개체에서 호출되고 원래 개체를 수정합니다.

NumPy 배열에 요소 추가

NumPy 모듈을 사용하면 NumPy append()insert() 함수를 사용하여 배열에 요소를 추가할 수 있습니다.

Syntax Description
numpy.append(arr, values, axis=None) Appends the values or array to the end of a copy of arr. If the axis is not provided, then default is None, which means both arr and values are flattened before the append operation.
numpy.insert(arr, obj, values, axis=None) Inserts the values or array before the index (obj) along the axis. If the axis is not provided, then the default is None, which means that only arr is flattened before the insert operation.

numpy.append() 함수는 백그라운드에서 numpy.concatenate() 함수를 사용합니다. numpy.concatenate()를 사용하여 기존 축을 따라 일련의 배열을 결합할 수 있습니다. NumPy 설명서에서 배열 조작 루틴에 대해 자세히 알아보세요.

참고: 이 섹션의 예제 코드를 테스트하려면 NumPy를 설치해야 합니다.

이 섹션의 예제에서는 2차원(2D) 배열을 사용하여 제공한 축 값에 따라 함수가 배열을 조작하는 방법을 강조합니다.

numpy.append()를 사용하여 배열에 추가

NumPy 배열은 크기와 모양으로 설명할 수 있습니다. 값 또는 배열을 다차원 배열에 추가할 때 추가되는 배열 또는 값은 지정된 축을 제외하고 동일한 모양이어야 합니다.

2D 배열의 모양을 이해하려면 행과 열을 고려하십시오. array([[1, 2], [3, 4]])는 2행 2열에 해당하는 2, 2 모양을 갖는 반면 array( [[10, 20, 30], [40, 50, 60]])는 2행 3열에 해당하는 2, 3 모양을 가집니다.

Python 대화형 콘솔을 사용하여 이 개념을 테스트합니다.

먼저 NumPy 모듈을 가져온 다음 배열을 만들고 모양을 확인합니다.

NumPy를 가져온 다음 np_arr1을 만들고 인쇄합니다.

  1. import numpy as np
  2. np_arr1 = np.array([[1, 2], [3, 4]])
  3. print(np_arr1)
Output
[[1 2] [3 4]]

np_arr1의 모양을 확인합니다.

  1. np_arr1.shape
Output
(2, 2)

다른 배열 np_arr2를 만들고 인쇄합니다.

  1. np_arr2 = np.array([[10, 20, 30], [40, 50, 60]])
  2. print(np_arr2)
Output
[[10 20 30] [40 50 60]]

np_arr2의 모양을 확인합니다.

  1. np_arr2.shape
Output
(2, 3)

그런 다음 다른 축을 따라 배열을 추가해 보십시오. 1 축을 따라 2, 2 모양의 배열에 2, 3 모양의 배열을 추가할 수 있습니다. 축 0.

축 0을 따라 또는 행별로 np_arr2np_arr1에 추가합니다.

  1. np.append(np_arr1, np_arr2, axis=0)

ValueError가 발생합니다.

Output
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<__array_function__ internals>", line 5, in append File "/Users/digitalocean/opt/anaconda3/lib/python3.9/site-packages/numpy/lib/function_base.py", line 4817, in append return concatenate((arr, values), axis=axis) File "<__array_function__ internals>", line 5, in concatenate ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 3

너비가 3열인 행이 있는 배열을 너비가 2열인 행이 있는 배열에 추가할 수 없습니다.

축 1을 따라 또는 열별로 np_arr2np_arr1에 추가합니다.

  1. np.append(np_arr1, np_arr2, axis=1)

출력은 다음과 같습니다.

Output
array([[ 1, 2, 10, 20, 30], [ 3, 4, 40, 50, 60]])

2행 높이의 열이 있는 배열을 2행 높이의 열이 있는 다른 배열에 추가할 수 있습니다.

다음 예제는 numpy.append() 함수를 사용하여 NumPy 배열에 요소를 추가하는 방법을 보여줍니다.

import numpy as np

# create 2D array objects (integers)
np_arr1 = np.array([[1, 2], [3, 4]])
np_arr2 = np.array([[10, 20], [30, 40]])

# print the arrays
print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)

# append an array to the end of another array and print the result
# both arrays are flattened before appending
append_axis_none = np.append(np_arr1, np_arr2, axis=None)
print("append_axis_none is:\n", append_axis_none)

# append an array to the end of another array along axis 0 (append rows)
# and print the result
append_axis_0 = np.append(np_arr1, np_arr2, axis=0)
print("append_axis_0 is:\n", append_axis_0)

# append an array to the end of another array along axis 1 (append columns)
# and print the result
append_axis_1 = np.append(np_arr1, np_arr2, axis=1)
print("append_axis_1 is:\n", append_axis_1)

출력은 다음과 같습니다.

Output
np_arr1 is: [[1 2] [3 4]] np_arr2 is: [[10 20] [30 40]] append_axis_none is: [ 1 2 3 4 10 20 30 40] append_axis_0 is: [[ 1 2] [ 3 4] [10 20] [30 40]] append_axis_1 is: [[ 1 2 10 20] [ 3 4 30 40]]

앞의 예제는 2D 배열의 각 축에 대해 numpy.append() 함수가 작동하는 방식과 결과 배열의 모양이 변경되는 방식을 보여줍니다. 축이 0이면 배열이 행 단위로 추가됩니다. 축이 1이면 배열에 열이 추가됩니다.

numpy.insert()를 사용하여 배열에 추가하기

numpy.insert() 함수는 축을 따라 지정된 인덱스 앞에 다른 배열에 배열 또는 값을 삽입하고 새 배열을 반환합니다.

numpy.append() 함수와 달리 축이 제공되지 않거나 None으로 지정된 경우 numpy.insert() 함수는 평면화됩니다. 첫 번째 배열만, 삽입할 값이나 배열을 평면화하지 않습니다. 축을 지정하지 않고 2D 배열에 2D 배열을 삽입하려고 하면 ValueError가 발생합니다.

다음 예제는 numpy.insert() 함수를 사용하여 배열에 요소를 삽입하는 방법을 보여줍니다.

import numpy as np

# create array objects (integers)
np_arr1 = np.array([[1, 2], [4, 5]])
np_arr2 = np.array([[10, 20], [30, 40]])
np_arr3 = np.array([100, 200, 300])

# print the arrays
print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)
print("np_arr3 is:\n", np_arr3)

# insert a 1D array into a 2D array and then print the result
# the original array is flattened before insertion
insert_axis_none = np.insert(np_arr1, 1, np_arr3, axis=None)
print("insert_axis_none is:\n", insert_axis_none)

# insert an array into another array by row
# and print the result
insert_axis_0 = np.insert(np_arr1, 1, np_arr2, axis=0)
print("insert_axis_0 is:\n", insert_axis_0)

# insert an array into another array by column
# and print the result
insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1)
print("insert_axis_1 is:\n", insert_axis_1)

출력은 다음과 같습니다.

Output
np_arr1 is: [[1 2] [4 5]] np_arr2 is: [[10 20] [30 40]] insert_axis_none is: [ 1 100 200 300 2 4 5] insert_axis_0 is: [[ 1 2] [10 20] [30 40] [ 4 5]] insert_axis_1 is: [[ 1 10 30 2] [ 4 20 40 5]]

앞의 예에서 2D 배열을 축 1을 따라 다른 2D 배열에 삽입하면 np_arr2 내의 각 배열이 별도의 열로 np_arr1에 삽입되었습니다. 전체 2D 배열을 다른 2D 배열에 삽입하려면 obj 매개변수 색인 값 주위에 대괄호를 포함하여 전체 배열이 해당 위치 앞에 삽입되어야 함을 나타냅니다. 대괄호가 없으면 numpy.insert()는 배열을 지정된 인덱스 앞에 열로 순서대로 쌓습니다.

다음 예는 obj(색인) 매개변수 주위에 대괄호가 있거나 없는 출력을 보여줍니다.

import numpy as np

# create 2D array objects (integers)
np_arr1 = np.array([[1, 2], [3, 4]])
np_arr2 = np.array([[10, 20], [30, 40]])

# print the arrays
print("np_arr1 is:\n", np_arr1)
print("np_arr2 is:\n", np_arr2)

# insert an array, column by column, into another array
# and print the result
insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1)
print("insert_axis_1 is:\n", insert_axis_1)

# insert a whole array into another array by column
# and print the result
insert_index_axis_1 = np.insert(np_arr1, [1], np_arr2, axis=1)
print("insert_index_axis_1 is:\n", insert_index_axis_1)

출력은 다음과 같습니다.

Output
np_arr1 is: [[1 2] [3 4]] np_arr2 is: [[10 20] [30 40]] insert_axis_1 is: [[ 1 10 30 2] [ 3 20 40 4]] insert_index_axis_1 is: [[ 1 10 20 2] [ 3 30 40 4]]

앞의 예제는 인덱스 표기법에 따라 numpy.insert()가 열을 배열에 삽입하는 방법을 보여줍니다.

결론

이 기사에서는 배열 및 NumPy 모듈을 사용하여 배열에 요소를 추가했습니다. 더 많은 Python 자습서로 학습을 계속하십시오.