Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save numpy array into computer for later use in python

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?

like image 738
Daniel Montealegre Avatar asked Jun 23 '16 15:06

Daniel Montealegre


1 Answers

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!

like image 199
mkarts Avatar answered Oct 23 '22 13:10

mkarts