Javatpoint Logo
Javatpoint Logo

NumPy Array Iteration

NumPy provides an iterator object, i.e., nditer which can be used to iterate over the given array using python standard Iterator interface.

Consider the following example.

Example

Output:

Printing array:
[[ 1  2  3  4]
 [ 2  4  5  6]
 [10 20 39  3]]
Iterating over the array:
1 2 3 4 2 4 5 6 10 20 39 3 

Order of the iteration doesn't follow any special ordering like row-major or column-order. However, it is intended to match the memory layout of the array.

Let's iterate over the transpose of the array given in the above example.

Example

Output:

Printing the array:
[[ 1  2  3  4]
 [ 2  4  5  6]
 [10 20 39  3]]
Printing the transpose of the array:
[[ 1  2 10]
 [ 2  4 20]
 [ 3  5 39]
 [ 4  6  3]]
1 2 3 4 2 4 5 6 10 20 39 3 

Order of Iteration

As we know, there are two ways of storing values into the numpy arrays:

  1. F-style order
  2. C-style order

Let's see an example of how the numpy Iterator treats the specific orders (F or C).

Example

Output:

Printing the array:

[[ 1  2  3  4]
 [ 2  4  5  6]
 [10 20 39  3]]

Printing the transpose of the array:

[[ 1  2 10]
 [ 2  4 20]
 [ 3  5 39]
 [ 4  6  3]]

Iterating over the transposed array

1 2 3 4 2 4 5 6 10 20 39 3 
Sorting the transposed array in C-style:

[[ 1  2 10]
 [ 2  4 20]
 [ 3  5 39]
 [ 4  6  3]]

Iterating over the C-style array:

1 2 10 2 4 20 3 5 39 4 6 3 [[ 1  2 10]
 [ 2  4 20]
 [ 3  5 39]
 [ 4  6  3]]
Iterating over the F-style array:

1 2 3 4 2 4 5 6 10 20 39 3 

We can mention the order 'C' or 'F' while defining the Iterator object itself. Consider the following example.

Example

Output:

Iterating over the transposed array

1 2 3 4 2 4 5 6 10 20 39 3
Sorting the transposed array in C-style:


Iterating over the C-style array:

1 2 10 2 4 20 3 5 39 4 6 3 

Array Values Modification

We can not modify the array elements during the iteration since the op-flag associated with the Iterator object is set to readonly.

However, we can set this flag to readwrite or write only to modify the array values. Consider the following example.

Example

Output:

Printing the original array:

[[ 1  2  3  4]
 [ 2  4  5  6]
 [10 20 39  3]]

Iterating over the modified array

3 6 9 12 6 12 15 18 30 60 117 9 






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA