iterate and modify array with numpy

  • Last Update :
  • Techknowledgy :

The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array.,NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface.,NumPy - Iterating Over Array,If the same elements are stored using F-style order, the iterator chooses the more efficient way of iterating over an array.

1._
import numpy as np
a = np.arange(0, 60, 5)
a = a.reshape(3, 4)

print 'Original array is:'
print a
print '\n'

print 'Modified array is:'
for x in np.nditer(a):
   print x,

The output of this program is as follows −

Original array is: [
   [0 5 10 15]
   [20 25 30 35]
   [40 45 50 55]
]

Modified array is:
   0 5 10 15 20 25 30 35 40 45 50 55
3._
import numpy as np
a = np.arange(0, 60, 5)
a = a.reshape(3, 4)

print 'Original array is:'
print a
print '\n'

print 'Transpose of the original array is:'
b = a.T
print b
print '\n'

print 'Modified array is:'
for x in np.nditer(b):
   print x,
5._
import numpy as np
a = np.arange(0, 60, 5)
a = a.reshape(3, 4)
print 'Original array is:'
print a
print '\n'

print 'Transpose of the original array is:'
b = a.T
print b
print '\n'

print 'Sorted in C-style order:'
c = b.copy(order = 'C')
print c
for x in np.nditer(c):
   print x,

   print '\n'

print 'Sorted in F-style order:'
c = b.copy(order = 'F')
print c
for x in np.nditer(c):
   print x,

Its output would be as follows −

Original array is: [
   [0 5 10 15]
   [20 25 30 35]
   [40 45 50 55]
]

Transpose of the original array is: [
   [0 20 40]
   [5 25 45]
   [10 30 50]
   [15 35 55]
]

Sorted in C - style order: [
   [0 20 40]
   [5 25 45]
   [10 30 50]
   [15 35 55]
]
0 20 40 5 25 45 10 30 50 15 35 55

Sorted in F - style order: [
   [0 20 40]
   [5 25 45]
   [10 30 50]
   [15 35 55]
]
0 5 10 15 20 25 30 35 40 45 50 55

Suggestion : 2

I just copied this from the official documentation:

>>> a = np.arange(6).reshape(2, 3) >>>
   a
array([
      [0, 1, 2],
      [3, 4, 5]
   ]) >>>
   for x in np.nditer(a, op_flags = ['readwrite']):
   ...x[...] = 2 * x
   ...
   >>>
   a
array([
   [0, 2, 4],
   [6, 8, 10]
])

You may want to work on vectors and not loops?

In[144]: cakes = np.array([2, 3])

In[145]: cakes * 2 + 2
Out[145]: array([6, 8])

As it is though, the numpyonic way of doing this looks like:

ingredient = cakes * 2 + 2

Use vectorization:

ingredient = cakes * 2 + 2

Suggestion : 3

By default, the nditer treats the input operand as a read-only object. To be able to modify the array elements, you must specify either read-write or write-only mode using the ‘readwrite’ or ‘writeonly’ per-operand flags.,The nditer will then yield writeable buffer arrays which you may modify. However, because the nditer must copy this buffer data back to the original array once iteration is finished, you must signal when the iteration is ended, by one of two methods. You may either:,The most basic task that can be done with the nditer is to visit every element of an array. Each element is provided one by one using the standard Python iterator interface.,By default, the nditer uses the flags ‘allocate’ and ‘writeonly’ for operands that are passed in as None. This means we were able to provide just the two operands to the iterator, and it handled the rest.

>>> a = np.arange(6).reshape(2, 3) >>>
   for x in np.nditer(a):
   ...print(x, end = ' ')
   ...
   0 1 2 3 4 5
>>> a = np.arange(6).reshape(2, 3) >>>
   for x in np.nditer(a.T):
   ...print(x, end = ' ')
   ...
   0 1 2 3 4 5
>>>
for x in np.nditer(a.T.copy(order = 'C')):
   ...print(x, end = ' ')
   ...
   0 3 1 4 2 5
>>> a = np.arange(6).reshape(2, 3) >>>
   for x in np.nditer(a, order = 'F'):
   ...print(x, end = ' ')
   ...
   0 3 1 4 2 5 >>>
   for x in np.nditer(a.T, order = 'C'):
   ...print(x, end = ' ')
   ...
   0 3 1 4 2 5
>>> a = np.arange(6).reshape(2, 3) >>>
   a
array([
      [0, 1, 2],
      [3, 4, 5]
   ]) >>>
   with np.nditer(a, op_flags = ['readwrite']) as it:
   ...
   for x in it:
   ...x[...] = 2 * x
   ...
   >>>
   a
array([
   [0, 2, 4],
   [6, 8, 10]
])
>>> a = np.arange(6).reshape(2, 3) >>>
   for x in np.nditer(a, flags = ['external_loop']):
   ...print(x, end = ' ')
   ...[0 1 2 3 4 5]

Suggestion : 4

for and while loop is used to iterate one-dimensional and two-dimensional array.,Numpy package provides an iterator object called numpy.nditer. nditer is a multi-dimensional iterator that enables you to iterate each element of Numpy array.,Note: The default order of iteration followed by nditer() is as per the memory layout of an array. This thing is noticable when you transpose an array and then iterate it.,In this tutorial, you will learn two different ways of iterating Numpy array-

Iterating a One-dimensional Array

#Python program to iterate 1 - D Numpy array using
for loop
import numpy as np

x = np.array([21, 15, 99, 42, 78])
for cell in x:
   print(cell, end = ' ')

Output of the above program

21 15 99 42 78
21 15 99 42 78
#Python program to iterate 1 - D Numpy array using
while loop
import numpy as np

x = np.array([21, 15, 99, 42, 78])
i = 0
while i < x.size:
   print(x[i], end = ' ')
i = i + 1

In case, you want to iterate each cell then go through the below examples-

#Python program to iterate each cell of 2 - D array using
for loop
import numpy as np

x = np.array([
   [21, 15, 99, 42, 78],
   [11, 54, 34, 76, 89]
])
for row in x:
   for cell in row:
   print(cell, end = ' ')
print()
21 15 99 42 78
11 54 34 76 89
#Python program to iterate each cell of 2 - D array using
while loop
import numpy as np

x = np.array([
   [21, 15, 99, 42, 78],
   [11, 54, 34, 76, 89]
])
i = 0
j = 0
rows, cols = x.shape
while i < rows:
   j = 0
while j < cols:
   print(x[i][j], end = ' ')
j = j + 1
print()
i = i + 1

Suggestion : 5

Last Updated : 15 Nov, 2018

NumPy package contains an iterator object numpy.nditer. It is an efficient multidimensional iterator object using which it is possible to iterate over an array. Each element of an array is visited using Python’s standard Iterator interface.

# Python program
for
# iterating over array

import numpy as geek

# creating an array using arrange
# method
a = geek.arange(12)

# shape array with 3 rows and
# 4 columns
a = a.reshape(3, 4)

print('Original array is:')
print(a)
print()

print('Modified array is:')

# iterating an array
for x in geek.nditer(a):
   print(x)

Output:

Original array is: [
   [0 1 2 3]
   [4 5 6 7]
   [8 9 10 11]
]

Modified array is:
   0 1 2 3 4 5 6 7 8 9 10 11

The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array.

# Python program
for
# iterating over transpose
# array

import numpy as geek

# creating an array using arrange
# method
a = geek.arange(12)

# shape array with 3 rows and
# 4 columns
a = a.reshape(3, 4)

print('Original array is:')
print(a)
print()

# Transpose of original array
b = a.T

print('Modified array is:')
for x in geek.nditer(b):
   print(x)

 
Code #2:

# Python program
for
# iterating over array
# using particular order

import numpy as geek

# creating an array using arrange
# method
a = geek.arange(0, 60, 5)

# shape array with 3 rows and
# 4 columns
a = a.reshape(3, 4)

print('Original array is:')
print(a)
print()

print('Modified array in F-style order:')

# iterating an array in a given
# order
for x in geek.nditer(a, order = 'F'):
   print(x)

Modifying Array Values:
The nditer object has another optional parameter called op_flags. Its default value is read-only, but can be set to read-write or write-only mode. This will enable modifying array elements using this iterator.

# Python program
for
# modifying array values

import numpy as geek

# creating an array using arrange
# method
a = geek.arange(12)

# shape array with 3 rows and
# 4 columns
a = a.reshape(3, 4)
print('Original array is:')
print(a)
print()

# modifying array values
for x in geek.nditer(a, op_flags = ['readwrite']):
   x[...] = 5 * x
print('Modified array is:')
print(a)

Suggestion : 6

numpy.nditer is an efficient multidimensional iterator object that is used to iterate over an array in the Numpy library., numpy.nditer is an efficient multidimensional iterator object that is used to iterate over an array in the Numpy library. ,Let us take a look at an example where we will create an ndarray using the arange() method and then iterate over it using numpy.nditer:,In this tutorial, we have covered the nditer object in Numpy which is used for the iteration over the arrays. After that, we have covered how the order of iteration plays a role in iteration with the help of an example. Then learned the Broadcasting Iteration along with its example. And finally we covered how to modify the values of array at the time of iteration.

Let us take a look at an example where we will create an ndarray using the arange() method and then iterate over it using numpy.nditer:

import numpy as np

a = np.arange(0, 40, 5)

print("The Original array is:")
print(a)
print('\n')

# showing elements of array one by one
print("The Modified array is:")
for x in np.nditer(a):
   print(x)

Let us take an example where we will take an array, then we will see the transpose of the given matrix and we will iterate using nditer. The code for the same is as follows:

import numpy as np

a = np.array([
   [11, 2, 3, 4],
   [29, 4, 15, 6],
   [11, 21, 39, 31]
])
print("The array is :")
print(a)

print("The transpose of the array is :")
at = a.T

print(at)
print("Iterating over the array:")
for x in np.nditer(at):
   print(x, end = ' ')

Below we have an example where we will iterate in F-style and C-style both. The code snippet for the same is as follows:

import numpy as np

a = np.array([
   [1, 2, 3, 4],
   [8, 9, 5, 6],
   [10, 20, 29, 31]
])
print("\nPrinting the array:\n")
print(a)
print("\nPrinting the transpose of the array:\n")
at = a.T
print(at)
print("\nIterating over the transposed array\n")

for x in np.nditer(at):
   print(x, end = ' ')
print("\nSorting the transposed array in C-style:\n")
c = at.copy(order = 'C')
print(c)

print("\nIterating over the C-style array:\n")
for x in np.nditer(c):
   print(x, end = ' ')

d = at.copy(order = 'F')
print("\n")
print(d)

print("\nIterating over the F-style array:\n")
for x in np.nditer(d):
   print(x, end = ' ')

The code example for the same is as follows:

import numpy as np

a = np.arange(0, 60, 5)
a = a.reshape(3, 4)

print('The First array :')
print(a)
print('\n')

print('The Second array is')
b = np.array([1, 2, 3, 4], dtype = int)
print(b)
print('\n')

print('The Modified array is')
for x, y in np.nditer([a, b]):
   print("%d:%d" % (x, y))

Let us take a look at the example for the same:

import numpy as np

a = np.arange(0, 50, 6)
a = a.reshape(3, 3)
print('The Original array is:')
print(a)
print('\n')
for x in np.nditer(a, op_flags = ['readwrite']):
   # modifying the value of array elements
x[...] = 2 + x
print('The Modified array is:')
print(a)

Suggestion : 7

As usual, we are importing a library and storing an array in a variable, but the only difference is using a two-dimensional array instead of a one-dimensional array.,An array is a special variable, and it holds more than one value at a time. Types of the array,one dimensional array andmultidimensional array.,nditer() is the most popular function in Numpy. The main purpose of the nditer() function is to iterate an array of objects. We can iterate multidimensional arrays using this function. We can also get a Transpose of an array which is simply known as converting a row into columns and columns into rows using “flags“.,Until we saw how to get a modified array, the same procedure is followed here, but we will get a transpose of an array here. for transpose we are using a statement flags=[‘external_loop’],order=’F’ which displays an array as a transpose of the original array.

Syntax of numpy nditer function:

for counter_variable in np.nditer(array): print(counter_variable)
2._
import numpy as np
a = np.array([2, 4, 5])
print("Original array is :")
print(a)
print("Modified array is:")
for x in np.nditer(a):
   print(x)

Output

Original array is: [2 4 5]
Modified array is:
   2
4
5

Output

Original array is: [
   [2 4 5]
   [3 6 8]
]
Modified array is:
   2
4
5
3
6
8
6._
import numpy as np
a = np.array([
   [2, 4, 5],
   [3, 6, 7],
   [4, 8, 9]
])
print("Original array is :")
print(a)
print("Modified array is:")
for x in np.nditer(a):
   print(x)
import numpy as np
a = np.array([2, 4, 5])
print("Original array is :")
print(a)
print("Modified array is:")
for x in np.nditer(a):
   print(x)
import numpy as np
a = np.array([
   [2, 4, 5],
   [3, 6, 8]
])
print("Original array is :")
print(a)
print("Modified array is:")
for x in np.nditer(a):
   print(x)
import numpy as np
a = np.array([
   [2, 4, 5],
   [3, 6, 7],
   [4, 8, 9]
])
print("Original array is :")
print(a)
print("Modified array is:")
for x in np.nditer(a):
   print(x)
import numpy as np
a = np.array([
   [2, 4, 5],
   [3, 6, 7],
   [4, 8, 9]
])
print("Original array is :")
print(a)
print("Modified array is:")
for x in np.nditer(a, flags = ['external_loop'], order = 'F'):
   print(x)