Tuesday, January 25, 2022

Adding Items in a NumPy Array

To add the items into a NumPy array, you can use the append() method from the NumPy module. First, you need to pass the original array and the item that you want to append to the array to the append() method. The append() method returns a new array that contains newly added items appended to the end of the original array.

The following script adds a text item “Yellow” to an existing array with three items.

my_array = np.array(["Red", "Green", "Orange"])

print(my_array)

extended = np.append(my_array, "Yellow")

print(extended)

Output:

['Red' 'Green' 'Orange']

['Red' 'Green' 'Orange' 'Yellow']

In addition to adding one item at a time, you can also append an array of items to an existing array. The method remains similar to appending a single item. You just have to pass the existing array and the new array to the append() method, which returns a concatenated array where items from the new array are appended at the end of the original array.

my_array = np.array(["Red", "Green", "Orange"])

print(my_array)

extended = np.append(my_array, ["Yellow", "Pink"])

print(extended)

Output:

['Red' 'Green'['Red' 'Green' 'Orange']

['Red' 'Green' 'Orange' 'Yellow' 'Pink']

To add items in a two-dimensional NumPy array, you have to specify whether you want to add the new item as a row or as a column. To do so, you can take the help of the axis attribute of the append method.

Let’s first create a 3 x 3 array of all zeros.

zeros_array = np.zeros((3,3))

print(zeros_array)

The output shows all the rows from our two-dimensional NumPy array.

Output:

[[0. 0. 0.]

[0. 0. 0.]

[0. 0. 0.]]

To add a new row in the above 3 x 3 array, you need to pass the original array to the new array in the form of a row vector and the axis attribute to the append() method. To add a new array in the form of a row, you need to set 0 as the value for the axis attribute.

Here is an example script.

zeros_array = np.zeros((3,3))

print(zeros_array)

print("Extended Array")

extended = np.append(zeros_array, [[1, 2, 3]], axis = 0)

print(extended)

In the output below, you can see that a new row has been appended to our original 3 x 3 array of all zeros.

Output:

[[0. 0. 0.]

[0. 0. 0.]

[0. 0. 0.]]

Extended Array

[[0. 0. 0.]

[0. 0. 0.]

[0. 0. 0.]

[1. 2. 3.]]

To append a new array as a column in the existing 2-D array, you need to set the value of the axis attribute to 1.

zeros_array = np.zeros((3,3))

print(zeros_array)

print("Extended Array")

extended = np.append(zeros_array, [[1],[2],[3]], axis = 1)

print(extended)

Output:

[[0. 0. 0.]

[0. 0. 0.]

[0. 0. 0.]]

Extended Array

[[0. 0. 0. 1.]

[0. 0. 0. 2.]

[0. 0. 0. 3.]]

The topic of discussion for our next post will be removing Items from a NumPy Array. Don't forget to practice and revise whatever we have covered so far

Share:

0 comments:

Post a Comment