08-19-2022, 06:55 PM
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.
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.
After importing the NumPy library, this library is referenced by calling the shortcode ().
Method 1: Use a For Loop and np.array()
This method uses aloop combined with to iterate through a 1D NumPy array. The first five (5) Atomic Numbers from the Periodic Table are generated and displayed for this example.
Above, calls the function and passes it 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 .
Next, a loop is instantiated and iterates through each element of the 1D NumPy array .
The output is sent to the terminal on one (1) line as an additional argument was passed to the print statement (). This argument replaces the default newline character with a blank space.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fs55BEAJRTOk%2Fhqdefault.jpg)
Method 2: Uses a For Loop and nditer()
This method uses a https://blog.finxter.com/python-loops/ loop combined with https://blog.finxter.com/how-to-initiali...easy-ways/ 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.
Above, calls the function and passes https://blog.finxter.com/python-range-fu...h%20Gauss. as the first argument and an array of associated Number of [b]Neutrons[/b] values as the second.
Next, an outer loop is instantiated. This iterates through each array dimension.
Inside this loop, another 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 (). This argument replaces the default newline character with a blank space.
Note: The first dimension is highlighted to easily differentiate the dimensions.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fvcu2Q-6sr-Q%2Fhqdefault.jpg)
Method 3: Use a For Loop and itertools
This method uses a loop and Python’s built-in 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.
Above, imports the library to use the 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, , and .
Next, a loop is instantiated and passed three (3) arguments inside the brackets which reference the arguments inside the function.
An additional argument () 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.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYyliq2-hVDw%2Fhqdefault.jpg)
Method 4: Use a While Loop and Size
This method uses a loop combined with https://blog.finxter.com/how-to-initiali...easy-ways/ 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.
Above, calls the function and passes a list containing the first five (5) element names of the Periodic Table. These results save to .
Then, a variable,, is declared with a start value of zero (). This will be a counter variable and lets the loop know when to stop iterating.
Next, a loop is instantiated and iterates through the elements of . This will continue while the value of remains less than the value of .
The output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (). This argument replaces the default newline character with a blank space.
Method 5: Use a For Loop and np.ndenumerate()
This method uses a loop and to iterate through a NumPy array. The first five (5) Element Names from the Periodic Table display for this example.
Above, calls the function and passes it an array containing the first five (5) element names from the Periodic Table. The results save to .
Next, a loop is instantiated referencing which is the index of the array, and , which is the array element’s value.
The output is sent to the terminal. Then displays a containing the index value of the array and then the value of for each iteration.
Method 6: Use a For Loop and range()
This method uses a loop and ) to iterate through a 3D NumPy array.
Above declares a 3D NumPy array containing consecutive numbers from 1-29 inclusive. These save to.
Next, three (3) loops are instantiated to loop through and output the contents of 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:
![[Image: kath-01aa.png]](https://blog.finxter.com/wp-content/uploads/2022/08/kath-01aa.png)
![[Image: kath-01b.png]](https://blog.finxter.com/wp-content/uploads/2022/08/kath-01b.png)
![[Image: kath-01bb.png]](https://blog.finxter.com/wp-content/uploads/2022/08/kath-01bb.png)
Finally, the output is sent to the terminal (snippet only).
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
To follow along, save this file as and move it into the current working directory.
Before moving forward, please ensure the Pandas library is installed. Click here if you require instructions.
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.
On the highlighted line, the function is called and passed the following arguments.
The results save to and output to the terminal.
![[Image: lyteCache.php?origThumbUrl=https%3A%2F%2...efault.jpg]](https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-JKVy_HliQE%2Fhqdefault.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
[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]
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.
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:
- Method 1: Use a loop andCode:
ForCode:np.array()
- Method 2: Use a https://blog.finxter.com/for-else-and-wh...ful-guide/loop andCode:
ForCode:np.nditer()
- Method 3: Use a https://blog.finxter.com/for-else-and-wh...ful-guide/loop andCode:
ForCode:itertools
- Method 4: Use a loop andCode:
WhileCode:np.size
- Method 5: Use a loop andCode:
ForCode:np.ndenumerate()
- Method 6: Use a Loop andCode:
ForCode:range()
- Bonus: CSV to Code:
np.array()
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 npAfter importing the NumPy library, this library is referenced by calling the shortcode (
Code:
npMethod 1: Use a For Loop and np.array()
This method uses a
Code:
ForCode:
np.array()Code:
atomic_els = np.array(np.arange(1,6)) for el in atomic_els: print(el, end=' ')Above, calls the
Code:
np.array()Code:
np.arange(1,6)Code:
atomic_elsCode:
[1 2 3 4 5]Next, a
Code:
ForCode:
atomic_elsThe output is sent to the terminal on one (1) line as an additional argument was passed to the print statement (
Code:
end=' 'Code:
1 2 3 4 5Method 2: Uses a For Loop and nditer()
This method uses a https://blog.finxter.com/python-loops/
Code:
forCode:
np.nditer()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()Code:
np.arange(1,6)Next, an outer
Code:
forInside this loop, another
Code:
forThe output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (
Code:
end=' 'Code:
1 2 3 4 5 0 2 4 5 6
Note: The first dimension is highlighted to easily differentiate the dimensions.Method 3: Use a For Loop and itertools
This method uses a
Code:
forCode:
itertoolsCode:
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:
itertoolsCode:
zip_longest()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_numCode:
atomic_phaseCode:
atomic_groupNext, a
Code:
forCode:
(a, b, c)Code:
zip_longest(atomic_num, atomic_phase, atomic_group)An additional argument (
Code:
fillvalue=0The loop iterates until the end of the arrays are reached, outputting to the terminal for each iteration.
Code:
1 gas 12 gas 183 solid 1Method 4: Use a While Loop and Size
This method uses a
Code:
whileCode:
np.sizeCode:
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 += 1Above, calls the
Code:
np.array()Code:
atomic_namesThen, a variable,
Code:
el_countCode:
WhileNext, a
Code:
whileCode:
atomic_namesCode:
el_countCode:
atomic_names.sizeThe output is sent to the terminal on one (1) line as an additional argument is passed to the print statement (
Code:
end=' 'Code:
Hydrogen Helium Lithium Beryllium BoronMethod 5: Use a For Loop and np.ndenumerate()
This method uses a
Code:
ForCode:
np.ndenumerate()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()Code:
atomic_namesNext, a
Code:
forCode:
idxCode:
xThe output is sent to the terminal. Then
Code:
idxCode:
TupleCode:
xCode:
(0,) Hydrogen(1,) Helium(2,) Lithium(3,) Beryllium(4,) BoronMethod 6: Use a For Loop and range()
This method uses a
Code:
forCode:
range()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:
numsNext, three (3)
Code:
forCode:
numsThe range() function for each loop is based on the dimensions of the 3D Numpy array, for example:
- The first loop () identifies the total number of tows in the array.Code:
range(0,5
![[Image: kath-01aa.png]](https://blog.finxter.com/wp-content/uploads/2022/08/kath-01aa.png)
- The next loop () identifies the number of columns in the array.Code:
range(0,3
![[Image: kath-01b.png]](https://blog.finxter.com/wp-content/uploads/2022/08/kath-01b.png)
- The final loop () identifies the elements in each column in the array.Code:
range(0,2
![[Image: kath-01bb.png]](https://blog.finxter.com/wp-content/uploads/2022/08/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.csvCode:
1,1.007,02,4.002,23,6.941,44,9.012,55,10.811,66,12.011,67,14.007,7To follow along, save this file as
Code:
pt_sample.csvBefore 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_nameOn the highlighted line, the
Code:
np.array()- The function is passed as an argument and this argument passes theCode:
csv.reader()method to open the specified CSV file in read (Code:open()) mode, including theCode:rdelimiter (Code:field).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_dataCode:
[[ 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. ]]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
[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]

