![]() |
|
[Tut] How to Iterate over a NumPy Array - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Iterate over a NumPy Array (/thread-99825.html) |
[Tut] How to Iterate over a NumPy Array - xSicKxBot - 08-19-2022 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. 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:
![]()
![]()
![]() 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 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]
|