user3102241
user3102241

Reputation: 497

Use value of variable rather than keyword in python numpy.savez

numpy.savez

In the last example, using savez with **kwds, the arrays are saved with the keyword names.

outfile = TemporaryFile()
np.savez(outfile, x=x, y=y)
outfile.seek(0)
npzfile = np.load(outfile)
npzfile.files
['y', 'x']
npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

How would I use the actual value of a variable, such that:

x_name = 'foo'
y_name = 'bar'

np.savez(outfile, x_name=x, y_name=y)

Then

npzfile.files
['foo', 'bar']

Upvotes: 1

Views: 1722

Answers (1)

DSM
DSM

Reputation: 353239

You could make a dictionary and then use ** to pass its contents in the form of keyword arguments to np.savez. For example:

>>> x = np.arange(10)
>>> y = np.sin(x)
>>> x_name = 'foo'
>>> y_name = 'bar'
>>> outfile = TemporaryFile()
>>> np.savez(outfile, **{x_name: x, y_name: y})
>>> outfile.seek(0)
>>> npzfile = np.load(outfile)
>>> npzfile.files
['foo', 'bar']

Upvotes: 6

Related Questions