Python Forum

Full Version: Why can't numpy array be restored to a saved value?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why isn't the final value of the numpy array npary in the following code the same as the initial value before some but not all elements of the array were changed to a new value?

I know I am missing something basic here. I thought I understood the concepts of immutable vs mutable values but obviously I missed something.

My environment is Win10-64, Python 3.8.5, numpy 1.19.2.

Code and output follows. TIA for any help you can provide to cure my ignorance.

Peter

import numpy as np
import sys

if len(sys.argv) > 0:
    try:
        asz = int(sys.argv[1]) + 0
    except:
        asz = 4

npary = np.full([asz, asz, asz], 0, dtype=np.int32)
print("Array before change=\n{}".format(npary))
svary = npary[:, :, :]
npary[1:-1, 1:-1, 1:-1] = 1
print("Array after change=\n{}".format(npary))
npary = svary[:, :, :]
print("Array after restore=\n{}".format(npary))
Output:
Array before change= [[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]] Array after change= [[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]] [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]] Array after restore= [[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]] [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]]
Never mind, I found the numpy.copy function which does what I need.

Revised code below and output showing correct result (array values restored).

Sorry for wasting bandwidth.

Peter

import numpy as np
import sys

if len(sys.argv) > 0:
    try:
        asz = int(sys.argv[1]) + 0
    except:
        asz = 4

npary = np.full([asz, asz, asz], 0, dtype=np.int32)
print("Array before change=\n{}".format(npary))
svary = np.copy(npary, order='C')
npary[1:-1, 1:-1, 1:-1] = 1
print("Array after change=\n{}".format(npary))
npary = svary
print("Array after restore=\n{}".format(npary))
Output:
Array before change= [[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]] Array after change= [[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]] [[0 0 0 0] [0 1 1 0] [0 1 1 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]] Array after restore= [[[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]]