Why can't numpy array be restored to a saved value? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why can't numpy array be restored to a saved value? (/thread-31150.html) |
Why can't numpy array be restored to a saved value? - pjfarley3 - Nov-25-2020 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))
RE: Why can't numpy array be restored to a saved value? - pjfarley3 - Nov-25-2020 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))
|