Understand Array Copy in NumPy – NumPy Tutorial

By | September 23, 2021

It is easy to copy an array in numpy, however, there are some important tips you must concern. In this tutoiral, we will discuss this topic.

= is copy?

We can use “=” operater to copy an array.

For example:

import numpy as np

a = np.array([1, 2, 3, 4])
b = a
print(a)
print(b)

From this code, we can copy all values in array \(a\) to array \(b\).

Run this code, you will see:

[1 2 3 4]
[1 2 3 4]

It means \(b\) is same to \(a\).

However, \(a\) and \(b\) share the same memory space, which means \(b\) is changed, \(a\) is also can be changed.

For example:

b[1] = 100
print(a)
print(b)

Run this code, you will see:

[  1 100   3   4]
[  1 100   3   4]

We can find the value of \(b\) is changed, \(a\) is also be changed.

How to make \(a\) can not be changed? We can use numpy.copy() function.

Use numpy.copy() function to copy array

numpy.copy() is defined as:

numpy.copy(a, order='K', subok=False)

It will create a new array, which is same to \(a\). But they will share different memory space.

For example:

import numpy as np

a = np.array([1, 2, 3, 4])
b = np.copy(a)

b[1] = 100
print(a)
print(b)

In this code, the value of \(b\) is changed. Run this code, you will see:

[1 2 3 4]
[  1 100   3   4]

We can find the value of \(a\) is not changed.

To know more about numpy.copy(), you can view this tutorial:

Understand numpy.copy(): Return a New Array Copy – NumPy Tutorial

Leave a Reply