Notebook Snippets

As you’re building, we know that there are some common things you’ll need to do in a notebook (like save to your output directory). Below, we have provided some helpful code snippets that you may use in your notebooks.

If you would like to add one to the list, let us know in the Losant Forums.

Loading Input Data

Reading input files from the INPUT_DIR directory.

import os  
import pandas as pd

input_dir = os.path.join(os.environ['INPUT_DIR'])

dataset = pd.read_csv(input_dir, 'data.csv')

Saving to Output Directory

Saving output files to the OUTPUT_DIR directory.

import os

output_dir = os.path.join(os.environ['INPUT_DIR'])

# Code that generates files goes here ...

# save a csv
myData.to_csv(output_dir, 'myData.csv')

# save a file
myChart.get_figure().savefig(output_dir, 'myChart.png')

Making your Timestamp a Pandas Datetime Dataframe

After turning your input into a pandas dataframe, you may want the Timestamp field to be an actual datetime. Here is an example of how to do that:

# read data
dataset = pd.read_csv(os.path.join(os.environ['INPUT_DIR'], 'dataset.csv'))

# convert to datetime
dataset['Timestamp'] = pd.to_datetime(dataset['Timestamp'], unit='ms')

# Set the timestamp as the index (optional)
dataset.set_index('Timestamp', inplace=True)

Setting Notebook Environment Variables to Current Directory

When developing locally, you may just want to set your inputs and outputs to your present working directory. Here is an easy way to accomplish that:

INPUT_DIR=$(pwd) OUTPUT_DIR=$(pwd) jupyter notebook