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.

import numpy as np

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

Here A is:

[[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

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:

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

A will be:

[[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.

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.

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

A will be:

[[[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