Skip to main content

How to iterate Arrays in Numpy

How to iterate Arrays in Numpy
Hi guys welcome to another to edition on this platform. If you are new please do checkout our previous articles and subscribe to our YouTube to get the full video tutorial.

In this article we are going to see how to iterate arrays in NumPy. Let’s get a head start of what array iteration is all about.

Iterating simply means checking element one at a time in a program. They are many multi-dimensional arrays in NumPy. 

Iterating a One-dimensional Array:

We are going to go through one element at a time. This is mostly done using the ‘for’ loop

import numpy as np
A = np.arange(12)
for cell in A:
print (cell, end=' ')

OUTPUT:

How to iterate Arrays in Numpy
Iterating a two- dimensional array

In addition to the for loop, we are going to used another function called re.shape. Here we able to iterate array each in a row.

Here is an example where the two functions are involved

import numpy as np
A = np.arange(12).reshape(4,3)
for row in A:
print(row)

OUTPUT:

How to iterate Arrays in Numpy

In a case where you don’t to what to iterate two rows, there is a function called flatten that reduce a two – dimensional array into a one-dimensional array. Note that this flatten functions reduce a multi-dimensional array into the specific array that you want.

Iterating Using the Nditer Function

It is a basic tool in NumPy module that we can used to solve basic problems. With this function we are able to create order during iteration by using parameters.  If you specify a particular order, the nditer functions called it, following the position of the element called.

Iterating scalar each scalar element

With the simple scalar elements, we can use the n for loops

Examples 

import numpy as np
arr = np.array([['a' 'b'], ['c' 'd'], ['e' 'f']])
for x in np.nditer(arr):
print(x)
import numpy as np

OUTPUT:

How to iterate Arrays in Numpy

However, this is not possible with scalars with high dimensions

Just as we can iterate scalars using nditer function, this function can also be used to get order during iteration which is called the nditer iteration order.

Example 

To get the ‘C’ order (horizontal order)

import numpy as np
a = np.arange(12)
print('Modified array is:')
for x in np.nditer(a, flags = ['external_loop'], order = 'C'):
print(x)

With this order, the array created is arranged horizontally following the order specified.

OUTPUT:

How to iterate Arrays in Numpy
To get the Fortran order (vertical order)
import numpy as np
a = np.arange(12)
print('Modified array in F-style order:')
for x in np.nditer(a, order = 'F'):
print(x)

With this order, the array created is arranged vertically following the order specified

OUTPUT:

How to iterate Arrays in Numpy
Modifying NumPy arrays 

In modifying arrays while iterating, we can use the op_flags function. So, to update the elements in an array we can do the following steps:

import numpy as np
a = np.arange(12)
for x in np.nditer(a, op_flags = ['readwrite']):
x[...] = 5*x
print('Modified array is:')
print(a)

The op-flag tell the compiler to add 5 to the previous number. This is done in a continuous sequence

OUTPUT:

How to iterate Arrays in Numpy
Iterating Two Arrays Simultaneously

We can use a nditer function to iterate arrays simultaneously. Here is an example to get you understand better.

import numpy as np
a = np.arange(12)
a = a.reshape(3,4)
b = np.array([5, 6, 7, 8], dtype = int)
print('Modified array is:')
for x,y in np.nditer([a,b]):
print("%d:%d" % (x,y))

Example

NumPy tells compile the run the program at the same time while following the instruction of the nditer function

OUTPUT:

How to iterate Arrays in Numpy
As seen in this article, nditer iterator provide a basic way of touching all elements in an array. In addition to what we have seen in this article, they are more advanced iteration like Reduction Iteration, Outer Product Iteration.  Hope this session was interesting. Have a nice coding day guy 

Comments

Popular posts from this blog

Introduction to flask

Hello. Welcome to another session on this platform. If you are new here, please do checkout our previous articles on python programming language and stay excited on this session because we are entering into one of python’s web-based application called flask. In this article, we are going to see the following What is flask Prequistes Installation of flask in python Some of flask template engine. What is flask? Flask is one of python-based framework which is used to create web applications. Flight is a very light web framework. During installation, flask comes with pre-installed modules and functions which are used to backup your own web applications. Flask is very easy to understand and perfect go-to for beginners and with flask, a web server can run in less than 3 lines of code. Prequistes Before learning flask, we recommend the reader to have a basic mastery of python concepts. Installation of flask  Before installing flask, we have to checked if python has been installed or. If n...

How to generate random numbers using NumP1

Hello. Welcome to another edition on this platform. For more better understanding, do checkout our YouTube channel to get the video tutorial. In this article of today, we are going to see how to generate random numbers using any of the following methods: Generating a random number Generating a random float and integer Generating random number arrays Generating random number from an array What is a random number? This is a number which cannot be predicted before its occurrence. This number might not different every time. Programmatically, they are two categories of random numbers:     Pseudo-Random numbers       True Random numbers. Just as programs which are written by programmers are a set of instructions, we must follow an algorithm to generate random numbers. Random numbers which are generated using an algorithm are called Pseudo-Random numbers. To generate a true random number, it is important to get the data from sources such as the keyboards, mou...

Introduction to Django

Hello. Welcome to another session on this platform. If you are new here, please do checkout our previous articles on python programming language and stay excited on this session. we are entering into one of python’s application called Django. In this article, we are going to discuss the following: What is Django Why must we use Django  A brief history of Django Installation of Django Popularity of Django What is Django? Python has so many framework application and Django happen to be one of them. Being a python-based-framework, it is used to quickly create web applications.  When building websites, django provides similar ready-made components to handle user authentication, forms, a way to upload components. Why use django? Django is very fast. It takes applications from concept to applications very quickly Django has thousand available packages in it when it is installed. With django, we can launch web applications is a matter of hours. Django is a highly is secured and helps...