NUMPY ARRAY ITERATING

NUMPY ARRAY ITERATING

M.Ramya



Iterating Arrays in NumPy

Iteration means accessing elements of an array one by one.

With NumPy, we can easily iterate through arrays, including multi-dimensional ones, using Python’s basic for loops or NumPy’s helper functions.



Iterating 1-D Arrays

Program:

When iterating over a 1-D array, each element is accessed one by one:

import numpy as np

arr = np.array([1, 2, 3])

for x in arr:

print(x)

Output:

1
2
3

Iterating 2-D Arrays

Program:

In a 2-D array, iteration goes through each row:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

for x in arr:  

print(x)

Output:

[1 2 3]
[4 5 6]

Program:

To access each scalar value, you can nest loops:

arr = [[1, 2], [3, 4], [5, 6]]

for x in arr:

    for y in x:

        print(y)

Output:

1
2
3
4
5
6

Iterating 3-D Arrays

In a 3-D array, iteration goes through each 2-D array:

Program:

import numpy as np

arr = np.array([

    [[1, 2, 3], [4, 5, 6]],

    [[7, 8, 9], [10, 11, 12]]

])

for x in arr:

    print(x)

Output:

[[1 2 3]
 [4 5 6]]
[[7 8 9]
 [10 11 12]]

Program:

To access individual scalar values, use nested loops:

arr = [

    [[1, 2], [3, 4]],

    [[5, 6], [7, 8]]

]

for x in arr:

    for y in x:

        for z in y:

            print(z)

Output:

1
2
3
4
5
6
7
8

Iterating with np.nditer()

The nditer() function simplifies iterating through each scalar element, especially for high-dimensional arrays.

Program:

import numpy as np

arr = np.array([

    [[1, 2], [3, 4]],

    [[5,6 ], [7, 8]]

])

for x in np.nditer(arr):

    print(x)

Output:

1
2
3
4
5
6
7
8

Iterating with Data Type Conversion

You can use the op_dtypes argument in nditer() to change data types while iterating.

To enable this, set flags=['buffered'] to allow temporary memory allocation (buffering).

Program:

(iterate as strings):

import numpy as np

arr = np.array([1, 2, 3])

for x in np.nditer(arr, flags=['buffered'], op_dtypes=['S']):

    print(x)

Output:

b'1'
b'2'
b'3'

Iterating with Step Sizes

You can use slicing to skip elements during iteration.

Program:

(skip every other element):

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

for x in np.nditer(arr[:, ::2]):

    print(x)

Output:

1
3
5
7

Enumerated Iteration with np.ndenumerate()

Enumeration means accessing both the index and the value while iterating.

Program:

1-D array

import numpy as np

arr = np.array([1, 2, 3])

for idx, x in np.ndenumerate(arr):

    print(idx, x)

Output:

(0,)1
(1,)2
(2,)3

Program: 

2-D array

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

for idx, x in np.ndenumerate(arr):

    print(idx, x)

Output:

(0,0)1
(0,1)2
(0,2)3
(0,3)4
(1,0)5
(1,1)6
(1,2)7
(1,3)8




More topic in Numpy

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !