 Python

# How to iterate columns in Numpy

In this article, we will study how to iterate the columns of the NumPy array. We will see all the basic methods of that. We will also see some advanced methods of iteration like the nditer object method.

## Method 1: Using for loop

In this method will iterate the 1-D (dimensional) array with the help of the for loop. This is just a similar way to the other programming languages C, C++, Python, etc.

importnumpyasnp
Arr=np.arange(12)
forvalinArr:
print(val, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9 10 11

Line 1: We import the NumPy library as np. So that we can use this namespace (np) instead of the full name numpy.

Line 2: We created an array of 12 elements which looks like below:

array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

Line 3 to 4: We are now using a for loop to iterate each element of the array and print that element value.

## Method 2: Using while loop

In this method will iterate the 1-D (dimensional) array with the help of the while loop.

importnumpyasnp
Arr=np.arange(12)
i=0
whileArr[i] <Arr.size:
print(Arr[i])
i= i+1
if(i==Arr.size):
break

Output:

0

1

2

3

4

5

6

7

8

9

10

11

Line 4 to 8: In this while loop, the loop continues till the size of the array (Arr. size) is less than the Arr[i] because, as we know, the last element value will be 11 and the size of the array is 12. If the condition is true, then print that element and increment the iteration (i) value by 1. If the iteration value count is equal to the size of the array, then the break will call and exit the loop. The Arr.size will return the number of elements in the array.

## Method 3: Iterating a Two-dimensional Array

To iterate the two-dimensional array, we need the nested loop. But if we use the single for loop, then we iterate over the row only.

Let’s understand this with an example.

Arr=np.arange(12).reshape(4,3)
for row inArr:
print(row)

Output:

[0 1 2]

[3 4 5]

[6 7 8]

[ 9 10 11]

Line 2 to 3: We got the output row-wise because, with the help of the single loop, we could not iterate each cell of the 2-D array.

## Using the nested-loop.

Arr=np.arange(12).reshape(4,3)
for row inArr:
for cell in row:
print(cell, end='\t')
print("\n")

Output:

0 1 2

3 4 5

6 7 8

9 10 11

Line 2 to 5: In the above program, we use two loops to iterate a 2-D array. The first loop takes the row value from the Arr, and the next loop access all the elements of that row array and prints on the screen as shown in the output.

## Method 4: Using Flatten method

Another method is the flattened method. The flatten method converts the 2-D array to a single-dimensional array. We don’t need two for loops to iterate the 2-D array if we use the flatten method.

Arr=np.arange(12).reshape(4,3)
for cell inArr.flatten():
print(cell, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9 10 11

Line 2 to 3: The flatten () method converted the 2-D array to a 1-D array, and we iterate it just like the same way the 1-D array does. Here, we do not need to use two for loop.

## Method 5: Using nditer object

The NumPy also provides an additional method to iterate the 2-D array. This method is called the nditer method. In the previous example, we can also try with the nditer method as given below:

Arr=np.arange(12).reshape(4,3)
for cell innp.nditer(Arr):
print(cell, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9 10 11

Line 2 to 3: We pass our array to the nditer () method, and now we can access each element just as the flatten () method does.

## Nditer Iteration Order

We can also control the access method of the nditer by another parameter called order. If we specify the order as C, then the nditer access the elements horizontal wise, and if we specify the order as F, then it will access the elements vertically. Let’s understand this with an example of each order.

Order as C:

# C order iteration
Arr=np.arange(12).reshape(4,3)
for cell innp.nditer(Arr, order='C'):
print(cell, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9 10 11

If, we print the Arr only, we get the output as give below:

array([[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8],
[ 9, 10, 11]])

Now, as we use the nditer loop with the order as C. So, it will access the elements horizontally. So if we see in the above array output, our values should be 0,1,2, then 3, 4, 5, and so on. So our result is also in the same sequence, which shows that order C works horizontally.

Order as F:

# F order iteration
Arr=np.arange(12).reshape(4,3)
for cell innp.nditer(Arr, order='F'):
print(cell, end=' ')

Output:

0 3 6 9 1 4 7 10 2 5 8 11

If, we print the Arr only, we get the output as give below:

array([[ 0, 1, 2],

[ 3, 4, 5],

[ 6, 7, 8],

[ 9, 10, 11]])

Now, as we use the nditer loop with the order as F. So, it will access the elements vertically. So if we see in the above array output, our values should be 0,3,6,9, then 1, 4, 7,10, and so on. So our result is also in the same sequence, which shows that order F works vertically.

## Method 6: Modification to the values of NumPy array when using nditer

By default, the nditer treats the elements of the array as read-only, and we can’t modify it. If we try to do that, the NumPy will raise an error.

But, if we want to edit the values of the NumPy array, then we have to use another parameter called op_flags=[‘readwrite’].

Let’s understand this with an example:

for cell innp.nditer(Arr):
cell[...] =cell*2

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
in
1for cell innp.nditer(Arr):
---->2     cell[...] =cell*2

cell[...] =cell-3
Arr

Ouput:

array([[-3, -2, -1],
[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8]])

## Conclusion:

So in this article, we have studied all the methods to iterate the NumPy array. The best method is nditer. This nditer method is more advanced to handle the NumPy array elements. Here in this article, all the basic concepts will be clear, and you can also look at some more advanced methods of the nditer like Reduction iteration. These are the methods like Reduction iterations, which are the techniques to handle the NumPy array elements in different forms. 