Reputation: 117
So I am doing some computation and I want to play around with a big array in python. The problem is that if I want to do stuff to the array, then my code will rebuild the array (which takes a lot of time). Ideally I would like to:
-Run my code once, and create the array. -Save the array into my computer. -Load it in another project so I can play around with it.
I looked at the documentation for numpy and I tried
from tempfile import TemporaryFile
outfile = TemporaryFile()
np.save(outfile, x)
(where above x is my array).
However, I cannot seem to find an .npy file on my computer anywhere. (I am using PyCharm if that helps). So how can I save it, and also how can I load my array in another project?
Upvotes: 8
Views: 22915
Reputation: 709
Had the same Q and found this at numpy docs (though I found need to use arr_0 and arr_1 to ref the variables in the dictionary !)
#Store a single array
import numpy as np
np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
np.load('/tmp/123.npy')
array([[1, 2, 3],
[4, 5, 6]])
#Store multiple arrays as compressed data to disk, and load it again:
import numpy as np
a=np.array([[1, 2, 3], [4, 5, 6]])
b=np.array([1, 2])
np.savez('/tmp/123.npz', a=a, b=b)
data = np.load('/tmp/123.npz')
a1 = data['arr_0']
array([[1, 2, 3],
[4, 5, 6]])
b1 = data['arr_1']
array([1, 2])
Upvotes: 4
Reputation: 677
I am a bit confused why you need to use TemporaryFile, because as the documentation of it claims, the file created with TemporaryFile will cease to exist once it is closed, or else when your Python program exits. Also, this file will have no name so I believe that this is your problem and not np.save!
Now , to answer your question, try the following:
import numpy as np
a = np.ones(1000) # create an array of 1000 1's for the example
np.save('outfile_name', a) # save the file as "outfile_name.npy"
You can load your array next time you launch the Python interpreter with:
a = np.load('outfile_name.npy') # loads your saved array into variable a.
Hope this answers your question!
Upvotes: 23