3-3-2-7. Accessing, Deleting, and Inserting Elements Into ndarrays
meaning the elements in them can be changed after the array has been created.
NumPy arrays can also be sliced in many different ways.
This allows us to achieve any subset of the array we want.
You’ll often use slicing to separate data.
For example, when dividing a dataset into training,
cross validation, and testing sets.
We will start by looking how the elements of
a NumPy array can be accessed or modified by indexing.
Let’s create a rank one array that contains integers from one to five.
Elements can be accessed by specifying
their positions using indices inside square brackets.
Positive indices are used to specify positions from the beginning of the array.
Notice that to access the first element in the array,
we have to use index zero not one.
We can also use negative indices to specify positions from the end of the array.
Notice that the same element can be accessed using both negative and positive integers.
As mentioned earlier, positive indices are
used to access elements from the beginning of the array,
while negative indices are used to access elements from the end of the array.
Now, let’s see how we can modify the elements in an array.
We can do this by accessing the element we want to change,
and then reassigning it using the equal sign.
Let’s modify the array X we just created.
We can change the fourth element in X from four to 20.
We can also access and modify specific elements of rank two in NumPy arrays.
The only difference is that we need to provide
two indices separated by a comma inside the square brackets.
Here’s a three by three array containing the integers from one to nine.
Let’s access some elements in that array.
Remember that zero, comma,
zero refers to the element in the first row and the first column, which is one.
Elements in rank two arrays can also be modified in the same way.
We can change the zero, comma,
zero element, in X from one to 20 like this.
Now that we know how to access and modify elements in an array,
let’s take a look at how we can add and delete elements.
We can delete elements using NumPy’s delete function.
This function takes in an array,
list of indices to delete,
and an axis to delete from.
For rank one arrays,
the axis keyword is not required.
For rank two arrays,
axis zero is used to select rows and axis one is used to select columns.
Let’s see some examples.
Here is a rank one array,
we can delete the first and last element of X like this.
And here is a rank 2 array,
and delete the first and last column of Y like this.
We can add values to NumPy arrays using the append function.
This function takes in an array,
a list of elements to append,
and the axis to append it on.
Let’s see some examples.
We can append an element six to this rank one array like this.
And we can append multiple elements,
say seven and eight in a list like this.
In a rank two array,
we can append a new row containing 10,
11, and 12 like this.
And we can append a new column containing 10,
11, 12 like this.
Notice that when appending rows or columns to rank two NumPy arrays,
the rows and columns must have the correct shape to match the shape of the array.
Now, let’s see how we can insert values into NumPy arrays.
We can use the insert function for this,
which takes in an array,
index, elements, and axis.
This inserts the given list of elements to the array right before
the given index along the specified axis. Here’s a rank one array.
We can insert the integers three and four between these elements two and five like this.
In this rank two array,
we can insert a row between this first and last row like this.
And insert a column full of fives between the first and second column like this.
NumPy also allows us to stack NumPy arrays on top of each other or side by side.
The stacking is done using either NumPy’s Vstack for
vertical stacking or Hstack function for horizontal stacking.
It’s important to note that in order to stack arrays,
the shape of the arrays must match.
Consider this rank one and rank two array X and Y.
We can stack X on top of Y with Vstack like this.
And we can stack X on the right of Y with Hstack like this.
We need to reshape X to match the shape of Y before stacking it horizontally.
다양한 NumPy 배열을 만드는 방법을 알았으므로 이제
NumPy가 어떻게 데이터를 효과적으로 조작할 수 있는지 봅시다.
NumPy 배열은 변경 가능합니다.
즉, 배열이 생성된 후 요소의 요소를 변경할 수 있습니다.
NumPy 배열은 다양한 방법으로 슬라이스할 수도 있습니다.
이를 통해 우리가 원하는 배열의 하위 집합을 얻을 수 있습니다.
슬라이싱을 사용하여 데이터를 분리하는 경우가 많습니다.
예를 들어 데이터 세트를 훈련으로 나눌 때,
교차 검증 및 테스트 세트.
의 요소를 살펴보는 것으로 시작하겠습니다.
NumPy 배열은 인덱싱을 통해 액세스하거나 수정할 수 있습니다.
1에서 5까지의 정수를 포함하는 1순위 배열을 만들어 보겠습니다.
다음을 지정하여 요소에 액세스할 수 있습니다.
대괄호 안에 인덱스를 사용하여 위치.
양수 인덱스는 배열의 시작 부분에서 위치를 지정하는 데 사용됩니다.
배열의 첫 번째 요소에 액세스하려면
1이 아닌 인덱스 0을 사용해야 합니다.
음수 인덱스를 사용하여 배열 끝에서 위치를 지정할 수도 있습니다.
음수와 양의 정수를 모두 사용하여 동일한 요소에 액세스할 수 있습니다.
앞서 언급했듯이 긍정적인 지표는
배열의 시작 부분에서 요소에 액세스하는 데 사용됩니다.
음수 인덱스는 배열 끝에서 요소에 액세스하는 데 사용됩니다.
이제 배열의 요소를 수정하는 방법을 살펴보겠습니다.
변경하려는 요소에 액세스하여 이를 수행할 수 있습니다.
그런 다음 등호를 사용하여 다시 할당합니다.
방금 만든 배열 X를 수정해 보겠습니다.
X의 네 번째 요소를 4에서 20으로 변경할 수 있습니다.
NumPy 배열에서 2순위의 특정 요소에 액세스하고 수정할 수도 있습니다.
유일한 차이점은 다음을 제공해야 한다는 것입니다.
대괄호 안에 쉼표로 구분된 두 개의 인덱스.
다음은 1에서 9까지의 정수를 포함하는 3×3 배열입니다.
해당 배열의 일부 요소에 액세스해 보겠습니다.
0, 쉼표,
0은 첫 번째 행과 첫 번째 열의 요소(1인 경우)를 나타냅니다.
2순위 배열의 요소도 같은 방식으로 수정할 수 있습니다.
0, 쉼표,
0 요소, X에서 이와 같이 1에서 20까지.
이제 배열의 요소에 액세스하고 수정하는 방법을 알았으므로
요소를 추가하고 삭제하는 방법을 살펴보겠습니다.
NumPy의 삭제 기능을 사용하여 요소를 삭제할 수 있습니다.
이 함수는 배열을 취하고,
삭제할 인덱스 목록,
삭제할 축이 있습니다.
1순위 배열의 경우,
axis 키워드는 필요하지 않습니다.
2순위 배열의 경우,
축 0은 행을 선택하는 데 사용되고 축 1은 열을 선택하는 데 사용됩니다.
몇 가지 예를 살펴보겠습니다.
다음은 1순위 배열입니다.
이와 같이 X의 첫 번째 요소와 마지막 요소를 삭제할 수 있습니다.
다음은 2순위 배열입니다.
이렇게 Y의 첫 번째 열과 마지막 열을 삭제합니다.
추가 기능을 사용하여 NumPy 배열에 값을 추가할 수 있습니다.
이 함수는 배열을 취하고,
추가할 요소 목록,
그리고 그것을 추가할 축.
몇 가지 예를 살펴보겠습니다.
이와 같이 1순위 배열에 요소 6을 추가할 수 있습니다.
여러 요소를 추가할 수 있습니다.
이와 같은 목록에서 7과 8을 말하십시오.
2순위 배열에서,
10을 포함하는 새 행을 추가할 수 있습니다.
11, 12는 이런 식이다.
10을 포함하는 새 열을 추가할 수 있습니다.
11, 12 이렇게.
두 NumPy 배열의 순위를 매기기 위해 행이나 열을 추가할 때,
행과 열은 배열의 모양과 일치하도록 올바른 모양을 가져야 합니다.
이제 NumPy 배열에 값을 삽입하는 방법을 살펴보겠습니다.
이를 위해 삽입 기능을 사용할 수 있습니다.
배열을 취하는
인덱스, 요소 및 축.
이것은 주어진 요소 목록을 바로 앞에 배열에 삽입합니다.
지정된 축을 따라 지정된 인덱스입니다. 다음은 1순위 배열입니다.
이러한 요소 2와 5 사이에 정수 3과 4를 이렇게 삽입할 수 있습니다.
이 2순위 배열에서,
이렇게 첫 번째 행과 마지막 행 사이에 행을 삽입할 수 있습니다.
그리고 이렇게 첫 번째 열과 두 번째 열 사이에 5로 채워진 열을 삽입합니다.
NumPy를 사용하면 NumPy 배열을 서로 또는 나란히 쌓을 수 있습니다.
스태킹은 NumPy의 Vstack을 사용하여 수행됩니다.
수직 스태킹 또는 수평 스태킹을 위한 Hstack 기능.
배열을 쌓기 위해서는
배열의 모양이 일치해야 합니다.
이 1순위를 고려하고 2순위 배열 X와 Y를 고려하십시오.
이와 같이 Vstack을 사용하여 Y 위에 X를 쌓을 수 있습니다.
그리고 우리는 이와 같이 Hstack을 사용하여 Y의 오른쪽에 X를 쌓을 수 있습니다.
수평으로 쌓기 전에 Y의 모양과 일치하도록 X의 모양을 변경해야 합니다.
Accessing, Deleting, and Inserting Elements Into ndarrays
We strongly encourage you to type the commands that you have learned in this demo. However, the notebook file demonstrated in the video above is available at the bottom of this page.
Now that you know how to create a variety of ndarrays, we will now see how NumPy allows us to effectively manipulate the data within the ndarrays. NumPy ndarrays are mutable, meaning that the elements in ndarrays can be changed after the ndarray has been created. NumPy ndarrays can also be sliced, which means that ndarrays can be split in many different ways. This allows us, for example, to retrieve any subset of the ndarray that we want. Often in Machine Learning you will use slicing to separate data, as for example when dividing a data set into training, cross validation, and testing sets.
We will start by looking at how the elements of an ndarray can be accessed or modified by indexing. Elements can be accessed using indices inside square brackets, [ ]. NumPy allows you to use both positive and negative indices to access elements in the ndarray. Positive indices are used to access elements from the beginning of the array, while negative indices are used to access elements from the end of the array. Let’s see how we can access elements in rank 1 ndarrays:
Example 1. Access individual elements of 1-D array
# We create a rank 1 ndarray that contains integers from 1 to 5 x = np.array([1, 2, 3, 4, 5]) # We print x print() print('x = ', x) print() # Let's access some elements with positive indices print('This is First Element in x:', x[0]) print('This is Second Element in x:', x[1]) print('This is Fifth (Last) Element in x:', x[4]) print() # Let's access the same elements with negative indices print('This is First Element in x:', x[-5]) print('This is Second Element in x:', x[-4]) print('This is Fifth (Last) Element in x:', x[-1])
x = [1 2 3 4 5]
This is First Element in x: 1 This is Second Element in x: 2 This is Fifth (Last) Element in x: 5
This is First Element in x: 1 This is Second Element in x: 2 This is Fifth (Last) Element in x: 5
Notice that to access the first element in the ndarray we have to use the index 0 not 1. Also notice, that the same element can be accessed using both positive and negative indices. As mentioned earlier, positive indices are used to access elements from the beginning of the array, while negative indices are used to access elements from the end of the array.
Now let’s see how we can change the elements in rank 1 ndarrays. We do this by accessing the element we want to change and then using the =
sign to assign the new value:
Example 2. Modify an element of 1-D array
# We create a rank 1 ndarray that contains integers from 1 to 5 x = np.array([1, 2, 3, 4, 5]) # We print the original x print() print('Original:\n x = ', x) print() # We change the fourth element in x from 4 to 20 x[3] = 20 # We print x after it was modified print('Modified:\n x = ', x)
Original: x = [1 2 3 4 5]
Modified: x = [ 1 2 3 20 5]
Similarly, we can also access and modify specific elements of rank 2 ndarrays. To access elements in rank 2 ndarrays we need to provide 2 indices in the form [row, column]
. Let’s see some examples.
Example 3. Access individual elements of 2-D array
# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9 X = np.array([[1,2,3],[4,5,6],[7,8,9]]) # We print X print() print('X = \n', X) print() # Let's access some elements in X print('This is (0,0) Element in X:', X[0,0]) print('This is (0,1) Element in X:', X[0,1]) print('This is (2,2) Element in X:', X[2,2])
X = [[1 2 3] [4 5 6] [7 8 9]]
This is (0,0) Element in X: 1 This is (0,1) Element in X: 2 This is (2,2) Element in X: 9
Remember that the index [0, 0]
refers to the element in the first row, first column.
Elements in rank 2 ndarrays can be modified in the same way as with rank 1 ndarrays. Let’s see an example:
Example 4. Modify an element of 2-D array
# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9 X = np.array([[1,2,3],[4,5,6],[7,8,9]]) # We print the original x print() print('Original:\n X = \n', X) print() # We change the (0,0) element in X from 1 to 20 X[0,0] = 20 # We print X after it was modified print('Modified:\n X = \n', X)
Original: X = [[1 2 3] [4 5 6] [7 8 9]]
Modified: X = [[20 2 3] [ 4 5 6] [ 7 8 9]]
Now, let’s take a look at how we can add and delete elements from ndarrays. We can delete elements using the np.delete(ndarray, elements, axis)
function. This function deletes
the given list of elements
from the given ndarray
along the specified axis
. For rank 1 ndarrays the axis
keyword is not required. For rank 2 ndarrays, axis = 0
is used to select rows, and axis = 1
is used to select columns. Let’s see some examples:
Example 5. Delete elements
# We create a rank 1 ndarray x = np.array([1, 2, 3, 4, 5]) # We create a rank 2 ndarray Y = np.array([[1,2,3],[4,5,6],[7,8,9]]) # We print x print() print('Original x = ', x) # We delete the first and last element of x x = np.delete(x, [0,4]) # We print x with the first and last element deleted print() print('Modified x = ', x) # We print Y print() print('Original Y = \n', Y) # We delete the first row of y w = np.delete(Y, 0, axis=0) # We delete the first and last column of y v = np.delete(Y, [0,2], axis=1) # We print w print() print('w = \n', w) # We print v print() print('v = \n', v)
Original x = [1 2 3 4 5]
Modified x = [2 3 4]
Original Y = [[1 2 3] [4 5 6] [7 8 9]]
w = [[4 5 6] [7 8 9]]
v = [[2] [5] [8]]
numpy.append
Syntax:
numpy.append(array, values, axis=None)
It appends values to the end of an array. Refer here for more details about additional arguments.
Now, let’s see how we can append values to ndarrays. We can append values to ndarrays using the np.append(ndarray, elements, axis)
function. This function appends the given list of elements
to ndarray
along the specified axis
. Let’s see some examples:
Example 6. Append elements
# We create a rank 1 ndarray x = np.array([1, 2, 3, 4, 5]) # We create a rank 2 ndarray Y = np.array([[1,2,3],[4,5,6]]) # We print x print() print('Original x = ', x) # We append the integer 6 to x x = np.append(x, 6) # We print x print() print('x = ', x) # We append the integer 7 and 8 to x x = np.append(x, [7,8]) # We print x print() print('x = ', x) # We print Y print() print('Original Y = \n', Y) # We append a new row containing 7,8,9 to y v = np.append(Y, [[7,8,9]], axis=0) # We append a new column containing 9 and 10 to y q = np.append(Y,[[9],[10]], axis=1) # We print v print() print('v = \n', v) # We print q print() print('q = \n', q)
Original x = [1 2 3 4 5]
x = [1 2 3 4 5 6]
x = [1 2 3 4 5 6 7 8]
Original Y = [[1 2 3] [4 5 6]]
v = [[1 2 3] [4 5 6] [7 8 9]]
q = [[ 1 2 3 9] [ 4 5 6 10]]
Notice that when appending rows or columns to rank 2 ndarrays the rows or columns must have the correct shape, so as to match the shape of the rank 2 ndarray.
Now let’s see now how we can insert values to ndarrays. We can insert values to ndarrays using the np.insert(ndarray, index, elements, axis)
function. This function inserts the given list of elements
to ndarray
right before the given index
along the specified axis
. Let’s see some examples:
Example 7. Insert elements
# We create a rank 1 ndarray x = np.array([1, 2, 5, 6, 7]) # We create a rank 2 ndarray Y = np.array([[1,2,3],[7,8,9]]) # We print x print() print('Original x = ', x) # We insert the integer 3 and 4 between 2 and 5 in x. x = np.insert(x,2,[3,4]) # We print x with the inserted elements print() print('x = ', x) # We print Y print() print('Original Y = \n', Y) # We insert a row between the first and last row of y w = np.insert(Y,1,[4,5,6],axis=0) # We insert a column full of 5s between the first and second column of y v = np.insert(Y,1,5, axis=1) # We print w print() print('w = \n', w) # We print v print() print('v = \n', v)
Original x = [1 2 5 6 7]
x = [1 2 3 4 5 6 7]
Original Y = [[1 2 3] [7 8 9]]
w = [[1 2 3] [4 5 6] [7 8 9]]
v = [[1 5 2 3] [7 5 8 9]]
numpy.hstack and numpy.vstack
Syntax:
numpy.hstack(sequence_of_ndarray)
It returns a stacked array formed by stacking the given arrays in sequence horizontally (column-wise). See the in-depth details here.
numpy.vstack(sequence_of_ndarray)
It returns a stacked array formed by stacking the given arrays, will be at least 2-D, in sequence vertically (row-wise). See the in-depth details here.
NumPy also allows us to stack ndarrays on top of each other, or to stack them side by side. The stacking is done using either the np.vstack()
function for vertical stacking, or the np.hstack()
function for horizontal stacking. It is important to note that in order to stack ndarrays, the shape of the ndarrays must match. Let’s see some examples:
Example 8. Stack arrays
# We create a rank 1 ndarray x = np.array([1,2]) # We create a rank 2 ndarray Y = np.array([[3,4],[5,6]]) # We print x print() print('x = ', x) # We print Y print() print('Y = \n', Y) # We stack x on top of Y z = np.vstack((x,Y)) # We stack x on the right of Y. We need to reshape x in order to stack it on the right of Y. w = np.hstack((Y,x.reshape(2,1))) # We print z print() print('z = \n', z) # We print w print() print('w = \n', w)
x = [1 2]
Y = [[3 4] [5 6]]
z = [[1 2] [3 4] [5 6]]
w = [[3 4 1] [5 6 2]]
Supporting Materials
다음
댓글을 달려면 로그인해야 합니다.