Why can't numpy array be restored to saved value?
Christian Gollwitzer
auriocus at gmx.de
Thu Nov 26 03:26:25 EST 2020
Am 25.11.20 um 07:47 schrieb pjfarley3 at earthlink.net:
> 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[:, :, :]
Because this does not copy the array, rather it creates a view into the
original array. This is an optimization to avoid copying. If you want a
copy, do svary = npary.copy()
Christian
More information about the Python-list
mailing list