Showing posts with label Data. Show all posts
Showing posts with label Data. Show all posts

Wednesday, February 2, 2022

How to save data in Python

How to save data in Python

Save data in Python

Suppose we have spent a lot of calculations to get a result in Python and we want to save all the data in a separate file so that we can reuse it later.
This post suggests some methods to do that.

numpy.savez

numpy.savez is a method to save several arrays into a single file in uncompressed .npz format.

import numpy as np 

x_save = np.arange(10)

np.savez("data.npz", x=x_save) # save x_save with name "x" to file data.npz

data = np.load("data.npz") 

x_use = data["x"]

print(x_use) # get [0 1 2 3 4 5 6 7 8 9]

In the case that x_save is a dictionary, use allow_pickle=True in the np.load().

import numpy as np 

x_save = {"a": [1,2,3], "b": "hello from x_save"}

np.savez("data.npz", x=x_save) # save x_save with name "x" to file data.npz

data = np.load("data.npz",  allow_pickle=True) 

x_use = data["x"]

print(x_use) # get {'x': [1, 2, 3], 'y': 'hello from x_save'}

shelve

The second solution is to use the package Shelve.

A “shelf” object is a persistent, dictionary-like object. It can handle most of datatypes in Python.

The following demo shows us how to save the dictionary named save_dict.

import shelve
save_dict = {"a": 1, "b": 2} 
with shelve.open('mydata') as db:
    db["save_dict"] = save_dict 

Here db stands for database.

Now, the dictionary save_dict has been saved in the file mydata.db.
We can retrieve this dictionary with a new name use_dict as follows.

import shelve
with shelve.open('mydata') as db:
    use_dict = db["save_dict"]
print(use_dict)

The result we get should be {'a': 1, 'b': 2}. Done!

pickle

In practice, I couldn’t load the file saved by shelve in another Colab Notebook. So solution for this case is to use pickle instead of shelve.

import pickle
save_dict =  {"a":  1,  "b":  2}

with open("mydata.pkl", "wb") as f:
	pickle.dump(save_data, f)

with open("mydata.pkl", "rb") as f:
	output = pickle.load(f)

Friday, January 7, 2022

Save code from Colab to Drive

Save code from Colab to Drive

Save code in Google Colab to Google Drive

Assume that we are working with Python in Google Colab. Now we have an awesome algorithm called demo:

def demo():
    print("Hello the world from demo()") 

Question: How do we save this function to our Drive?

This Notebook can be found on Github.


A simple solution is to use the packages drive, os and the magic syntax %%writefile as follows.

Step 1. Create a folder in Drive

We first mount our drive to Colab.

from google.colab import drive
drive.mount('/content/drive')

A window will pop up and we have to connect our google acount to access the Drive.

Now, import os package to manipulate the files.

import os

Let’s move to our Drive, create a working folder and enter it.

os.cddir("/content/drive/MyDrive")
folder_name = "working"
os.mkdir(folder_name)
os.chdir(folderr_name)

Now, we are inside the folder working. We can check it by using the command os.getcwd().

Step 2. Save the function

Now we put the demo function into a script named learn_1.py and save it to the working folder by using the magic command %%writefile.

%%writefile learn_1.py 

def demo():
    print("Hello the world from demo()") 

Step 3. Reuse the function

In the future, you can re-use this function by doing as follows. Go to Goggle Colab and run the following code.

# go to the folder
from google.colab import drive
drive.mount('/content/drive')
import os
os.cddir("/content/drive/MyDrive/working")# the path of file learn_1.py

# begin your code 
from learn_1.py import demo
demo()

Again, we have connect to our Drive and will get the string "Hello the world from demo()" as desired.

Note. Make sure that we are being in the folder containing learn_1.py, otherwise, we cannot import it. In such case, we may create an empty folder named __init__.py in working folder. This set the whole folder working as a Python package, so you can import demo function by the command from working.learn_1 import demo assuming that we are in the path /content/drive/MyDrive containing working folder.

Popular Posts