NumPy Replace Value in Array Using a Small Array or Matrix – NumPy Tutorial

By | October 19, 2020

In this tutorial, we will introduce how to replace some value in a big numpy array using a small numpy array or matrix, which is very useful when you are processing images in python.

We will use some examples to show you how to do.

Example 1

We will create a 2D array using numpy.

  1. import numpy as np
  2. A = np.ones((5, 5))
  3. print(A)
import numpy as np

A = np.ones((5, 5))
print(A)

Here A is:

  1. [[1. 1. 1. 1. 1.]
  2. [1. 1. 1. 1. 1.]
  3. [1. 1. 1. 1. 1.]
  4. [1. 1. 1. 1. 1.]
  5. [1. 1. 1. 1. 1.]]
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]

We will create a small array with the shape 2 * 3

  1. B = np.array([[0, 1, 3], [0, 1, 1]], np.float32)
B = np.array([[0, 1, 3], [0, 1, 1]], np.float32)

If we want to replace values in A using B as follows:

NumPy replace values in a big array using a small array - example 1

We can do like this:

  1. A[2:4, 1:4] = B
  2. print(A)
A[2:4, 1:4] = B
print(A)

A will be:

  1. [[1. 1. 1. 1. 1.]
  2. [1. 1. 1. 1. 1.]
  3. [1. 0. 1. 3. 1.]
  4. [1. 0. 1. 1. 1.]
  5. [1. 1. 1. 1. 1.]]
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 0. 1. 3. 1.]
 [1. 0. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]

You should notice:

A[2:4], it means the A[2],A[3]. It does not contain A[4]

A[:,1:4], it starts with A[:,1], ends with A[:,3]

Example 2

In python image processing, An image data is a 3 dimensions numpy data. In this example, we will show you how to replace 3 dims numpy array.

  1. import numpy as np
  2. A = np.ones((5, 5, 3))
  3. B = np.array([[[2, 0, 3], [0, 2, 1]],[[0, 1, 3], [0, 1, 1]]], np.float32)
import numpy as np
A = np.ones((5, 5, 3))
B = np.array([[[2, 0, 3], [0, 2, 1]],[[0, 1, 3], [0, 1, 1]]], np.float32)

We will replace some values in A using B.

  1. A[2:4,2:4]=B
  2. print(A)
A[2:4,2:4]=B
print(A)

A will be:

  1. [[[1. 1. 1.]
  2. [1. 1. 1.]
  3. [1. 1. 1.]
  4. [1. 1. 1.]
  5. [1. 1. 1.]]
  6. [[1. 1. 1.]
  7. [1. 1. 1.]
  8. [1. 1. 1.]
  9. [1. 1. 1.]
  10. [1. 1. 1.]]
  11. [[1. 1. 1.]
  12. [1. 1. 1.]
  13. [2. 0. 3.]
  14. [0. 2. 1.]
  15. [1. 1. 1.]]
  16. [[1. 1. 1.]
  17. [1. 1. 1.]
  18. [0. 1. 3.]
  19. [0. 1. 1.]
  20. [1. 1. 1.]]
  21. [[1. 1. 1.]
  22. [1. 1. 1.]
  23. [1. 1. 1.]
  24. [1. 1. 1.]
  25. [1. 1. 1.]]]
[[[1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [2. 0. 3.]
  [0. 2. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [0. 1. 3.]
  [0. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]]]

Leave a Reply