Sunday, January 23, 2022

Printing NumPy Arrays

Depending on the dimensions, there are various ways to display the NumPy arrays. The simplest way to print a NumPy array is to pass the array to the print method, as you have already seen in the previous posts. An example is given below: 

my_array = np.array([10,12,14,16,20,25])

print(my_array)

Output:

[10 12 14 16 20 25]

You can also use loops to display items in a NumPy array. It is a good idea to know the dimensions of a NumPy array before printing the array on the console. To see the dimensions of a NumPy array, you can use the ndim attribute, which prints the number of dimensions for a NumPy array. To see the shape of your NumPy array, you can use the shape attribute.

print(my_array.ndim)

print(my_array.shape)

The script shows that our array is one-dimensional. The shape is (6,), which means our array is a vector with 6 items.

Output:

1 (6,)

To print items in a one-dimensional NumPy array, you can use a single foreach loop, as shown below:

for i in my_array:

print(i)

Output:

10

12

14

16

20

25

Now, let’s see another example of how you can use the for each loop to print items in a two-dimensional NumPy array.

The following script creates a two-dimensional NumPy array with four rows and five columns. The array contains random integers between 1 and 10. The array is then printed on the console.

integer_random = np.random.randint(1,11, size=(4, 5))

print(integer_random)

In the output below, you can see your newly created array.

Output:

[[ 7 7 10 9 8]

[ 6 10 2 5 9]

[ 2 9 2 10 2]

[ 9 6 3 2 1]]

Let’s now try to see the number of dimensions and shape of our NumPy array.

print(integer_random.ndim)

print(integer_random.shape)

The output below shows that our array has two dimensions and the shape of the array is (4,5), which refers to four rows and five columns.

Output:

2 (4, 5)

To traverse through items in a two-dimensional NumPy array, you need two foreach loops: one for each row and the other for each column in the row.

Let’s first use one for loop to print items in our two-dimensional NumPy array.

for i in my_array:

print(i)

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

Output:

[7 7 10 9 8]

[6 10 2 5 9]

[2 9 2 10 2]

[9 6 3 2 1]

To traverse through all the items in the two-dimensional array, you can use the nested for each loop, as follows:

for rows ininteger_random:

for column in rows:

print(column)

Output:

7

7

1

0

9

8

6

1

0

2

5

9

2

9

2

1

0

2

9

6

3

2

1

In the next post , you will see how to add, remove, and sort elements in a NumPy array.

Share:

0 comments:

Post a Comment