Assigning an NPZ value to a file

Can someone explain to me why this is not working:

Step 1) Create a simple NPZ file

import numpy as np
a1 = np.zeros((3,2), dtype=np.double)
np.savez('npzfile.npz', field1=a1)

      

Step 2) Open NPZ file and try assigning a value to it

npzfile = np.load('npzfile.npz')
npzfile['field1'][0,0] = 3.2
print npzfile['field1']

      

This gives me the following output:

[[ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]]

      

In other words, trying to assign an 3.2

array to an array did nothing. Why?

+3


source to share


2 answers


It looks like the pseudo-dict npzfile (actually a numpy.lib.npyio.NpzFile

) cannot be written. If you set a single variable to an array, you can write to it:

a = npzfile['field1']
a[0,0] = 3.2
print a

      



Interestingly, as opposed to a regular array, np.may_share_memory(a, npzfile['field1'])

returns False

, whereas if you set b=a

, np.may_share_memory(a, b)

returns True

. Extracting an array field1

from the npzfile pseudo-dal to a new variable creates a copy, which is not normal behavior if it was the standard numpy ndarray. I'm not familiar with the internals of a type numpy.lib.npyio.NpzFile

, but my guess is that although it type(npzfile['field1'])

is ndarray

, its memory is handled differently.

+3


source


Hope it's not too obvious, but I create from it dict

:

a = dict(npzfile)

      



You now have a dictionary that you can add and then np.savez

to a file. I would assume this loads everything into memory, which may or may not be what you want (based on @Saullo Castro's comment above).

0


source







All Articles