Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Iterate over a NumPy Array
1
How to Iterate over a NumPy Array

Rate this post

Problem Formulation and Solution Overview

In this article, you’ll learn how to iterate over a 1D, 2D and 3D NumPy array using Python.

When working with the NumPy library, you will encounter situations where you will need to iterate through a 1D, 2D and even a 3D array. This article will show you how to accomplish this task.

[Image: 1f4ac.png] Question: How would we write code to iterate through a [i]1D, 2D or 3D[/i] NumPy array?

We can accomplish this task by one of the following options:

Preparation

Before moving forward, please ensure the NumPy library is installed. Click here if you require instructions.

Then, add the following code to the top of each script. This snippet will allow the code in this article to run error-free.

Code:
import numpy as np

After importing the NumPy library, this library is referenced by calling the shortcode (
Code:
np
).

Method 1: Use a For Loop and np.array()

This method uses a
Code:
For
loop combined with
Code:
np.array()
to iterate through a 1D NumPy array. The first five (5) Atomic Numbers from the Periodic Table are generated and displayed for this example.

Code:
atomic_els = np.array(np.arange(1,6)) for el in atomic_els: print(el, end=' ')

Above, calls the
Code:
np.array()
function and passes it
Code:
np.arange(1,6)
with two (2) arguments: a start position of one (1) and stop position of five (5) or (stop-1). The result is an arrayhttps://blog.finxter.com/python-list-methods/of integers and saves to
Code:
atomic_els
.

Code:
[1 2 3 4 5]

Next, a
Code:
For
loop is instantiated and iterates through each element of the 1D NumPy array
Code:
atomic_els
.

The output is sent to the terminal on one (1) line as an additional argument was passed to the print statement (
Code:
end=' '
). This argument replaces the default newline character with a blank space.

Code:
1 2 3 4 5

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Method 2: Uses a For Loop and nditer()

This method uses a https://blog.finxter.com/python-loops/
Code:
for
loop combined with https://blog.finxter.com/how-to-initiali...easy-ways/
Code:
np.nditer()
to iterate through a NumPy array. The first five (5) Atomic Numbers and Number of Neutrons data from the Periodic Table display for this example.

Code:
atomic_data = np.array([np.arange(1,6), [0, 2, 4, 5, 6]]) for dim in atomic_data: for d in dim: print(d, end=' ')

Above, calls the
Code:
np.array()
function and passes https://blog.finxter.com/python-range-fu...h%20Gauss.
Code:
np.arange(1,6)
as the first argument and an array of associated Number of [b]Neutrons[/b] values as the second.

Next, an outer
Code:
for
loop is instantiated. This iterates through each array dimension.

Inside this loop, another
Code:
for
loop is instantiated. The inside loop iterates through each element of the above dimensions.

The output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (
Code:
end=' '
). This argument replaces the default newline character with a blank space.

Code:
1 2 3 4 5 0 2 4 5 6

[Image: 1f4a1.png]Note: The first dimension is highlighted to easily differentiate the dimensions.

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Method 3: Use a For Loop and itertools

This method uses a
Code:
for
loop and Python’s built-in
Code:
itertools
library to iterate through a NumPy array. The first three (3) Atomic Numbers, Phase, and Group data from the Periodic Table display for this example.

Code:
import itertools atomic_num = np.arange(1,4) atomic_phase = ['gas', 'gas', 'solid'] atomic_group = [1, 18, 1] for (a, b, c) in itertools.zip_longest(atomic_num, atomic_phase, atomic_group, fillvalue=0): print (a, b, c)

Above, imports the
Code:
itertools
library to use the
Code:
zip_longest()
function.

Then, three (3) arrays are declared containing the relevant data for the first three (3) elements from the Periodic Table. They save respectively to
Code:
atomic_num
,
Code:
atomic_phase
, and
Code:
atomic_group
.

Next, a
Code:
for
loop is instantiated and passed three (3) arguments inside the brackets
Code:
(a, b, c)
which reference the arguments inside the
Code:
zip_longest(atomic_num, atomic_phase, atomic_group)
function.

An additional argument (
Code:
fillvalue=0
) is also passed. This fills in any missing values for lists of unequal lengths with the stated value.

The loop iterates until the end of the arrays are reached, outputting to the terminal for each iteration.

Code:
1 gas 12 gas 183 solid 1

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Method 4: Use a While Loop and Size

This method uses a
Code:
while
loop combined with https://blog.finxter.com/how-to-initiali...easy-ways/
Code:
np.size
to iterate through a NumPy array. The first five (5) Atomic Numbers, Number of Neutrons, and Phase data from the Periodic Table display for this example.

Code:
atomic_names = np.array(['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron']) el_count = 0 while el_count < atomic_names.size: print(atomic_names[el_count], end=' ') el_count += 1

Above, calls the
Code:
np.array()
function and passes a list containing the first five (5) element names of the Periodic Table. These results save to
Code:
atomic_names
.

Then, a variable,
Code:
el_count
, is declared with a start value of zero (). This will be a counter variable and lets the
Code:
While
loop know when to stop iterating.

Next, a
Code:
while
loop is instantiated and iterates through the elements of
Code:
atomic_names
. This will continue while the value of
Code:
el_count
remains less than the value of
Code:
atomic_names.size
.

The output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (
Code:
end=' '
). This argument replaces the default newline character with a blank space.

Code:
Hydrogen Helium Lithium Beryllium Boron

Method 5: Use a For Loop and np.ndenumerate()

This method uses a
Code:
For
loop and
Code:
np.ndenumerate()
to iterate through a NumPy array. The first five (5) Element Names from the Periodic Table display for this example.

Code:
atomic_names = np.array(['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron']) for idx, x in np.ndenumerate(atomic_names): print(idx, x)

Above, calls the
Code:
np.array()
function and passes it an array containing the first five (5) element names from the Periodic Table. The results save to
Code:
atomic_names
.

Next, a
Code:
for
loop is instantiated referencing
Code:
idx
which is the index of the array, and
Code:
x
, which is the array element’s value.

The output is sent to the terminal. Then
Code:
idx
displays a
Code:
Tuple
containing the index value of the array and then the value of
Code:
x
for each iteration.

Code:
(0,) Hydrogen(1,) Helium(2,) Lithium(3,) Beryllium(4,) Boron

Method 6: Use a For Loop and range()

This method uses a
Code:
for
loop and
Code:
range()
) to iterate through a 3D NumPy array.

Code:
nums = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]], [[19, 20], [21, 22], [23, 23]], [[24, 25], [26, 27], [28, 29]]]) for x in range(0, 5): for y in range(0, 3): for z in range(0, 2): print(nums[x][y][z])

Above declares a 3D NumPy array containing consecutive numbers from 1-29 inclusive. These save to
Code:
nums
.

Next, three (3)
Code:
for
loops are instantiated to loop through and output the contents of
Code:
nums
to the terminal one (1) number per line.

The range() function for each loop is based on the dimensions of the 3D Numpy array, for example:
  • The first loop (
    Code:
    range(0,5
    ) identifies the total number of tows in the array.

[Image: kath-01aa.png]
  • The next loop (
    Code:
    range(0,3
    ) identifies the number of columns in the array.

[Image: kath-01b.png]
  • The final loop (
    Code:
    range(0,2
    ) identifies the elements in each column in the array.

[Image: kath-01bb.png]

Finally, the output is sent to the terminal (snippet only).

Code:
12345678910...

Bonus: Convert CSV to np.array()

This example reads in a snippet of the Periodic Table as a CSV file. This data is converted to a NumPy array and is output to the terminal.

The CSV file below contains the values of the Atomic Number, Atomic Mass, Number of Neutrons, and the Number of Electrons for the first seven (7) elements from the Periodic Table.

Contents of
Code:
pt_sample.csv


Code:
1,1.007,02,4.002,23,6.941,44,9.012,55,10.811,66,12.011,67,14.007,7

To follow along, save this file as
Code:
pt_sample.csv
and move it into the current working directory.

Before moving forward, please ensure the Pandas library is installed. Click here if you require instructions.

Code:
import pandas as pd import csv file_name = 'pt_sample.csv' df_data = np.array(list(csv.reader(open(file_name, 'r'), delimiter=','))).astype("float") print(df_data)

Above, imports the Pandas library and the CSV library. This is needed to work with DataFrames and read in the CSV file.

Then, a filename is declared and saves to
Code:
file_name
.

On the highlighted line, the
Code:
np.array()
function is called and passed the following arguments.
  • The
    Code:
    csv.reader()
    function is passed as an argument and this argument passes the
    Code:
    open()
    method to open the specified CSV file in read (
    Code:
    r
    ) mode, including the
    Code:
    field
    delimiter (
    Code:
    csv.reader(open(file_name, 'r'), delimiter=',')
    ).

  • The contents of the CSV file converts to a list.

  • This list converts to an
    Code:
    np.array()
    .

The results save to
Code:
df_data
and output to the terminal.

Code:
[[ 1. 1.007 0. ][ 2. 4.002 2. ][ 3. 6.941 4. ][ 4. 9.012 5. ][ 5. 10.811 6. ][ 6. 12.011 6. ][ 7. 14.007 7. ]]

[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]

Summary

These seven (7) methods of iterating a NumPy array should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!

Programmer Humor – Blockchain

[Image: image-31.png][i]“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source – xkcd[/i]
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: