Why can't numpy array be restored to saved value?
pjfarley3 at earthlink.net
pjfarley3 at earthlink.net
Wed Nov 25 03:03:14 EST 2020
Never mind, I found the numpy.copy function does what I need. Revised code
below works.
Sorry for wasting bandwidth.
Peter
--- nptest.py ---
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))
--- nptest.py ---
> -----Original Message-----
> From: pjfarley3 at earthlink.net <pjfarley3 at earthlink.net>
> Sent: Wednesday, November 25, 2020 1:48 AM
> To: 'python-list at python.org' <python-list at python.org>
> Subject: Why can't numpy array be restored to saved value?
>
> 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
>
> --- nptest.py ---
> 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))
> --- nptest.py ---
>
> --- 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]]]
> --- output ---
More information about the Python-list
mailing list