Skip to content

Latest commit

 

History

History
123 lines (98 loc) · 3.87 KB

notebook_template.org

File metadata and controls

123 lines (98 loc) · 3.87 KB

Notebook Template

Setup

;;(shell-command-to-string "jupyter kernelspec list")
import datetime
import sys
from typing import Any, List

import numpy as np
import pandas as pd
import plotly.express as px
from dotenv import dotenv_values
from IPython.display import Image
from plotly.graph_objs._figure import Figure
#sys.executable

Utils

def df_to_org(df: pd.DataFrame) -> List[List[Any]]:
    """
    Convert a Pandas DataFrame to a data structure that can be used by org table
    """
    # return tabulate(df, headers=df.columns, tablefmt="orgtbl")

    def convert_timestamp_to_iso(timestamp):
        if isinstance(timestamp, pd.Timestamp):
            return timestamp.isoformat()
        else:
            return timestamp

    df = df.map(convert_timestamp_to_iso)

    return [list(df)] + df.values.tolist()

def render_plotly(fig: Figure) -> Image:
    """
    Render plotly figure as a static PNG. Requires kaleido.
    """
    img_bytes = fig.to_image(format="png")
    return Image(img_bytes)

Code

df = pd.DataFrame({
    'A' : ['spam', 'eggs', 'spam', 'eggs'] * 6,
    'B' : ['alpha', 'beta', 'gamma'] * 8,
    'C' : [np.random.choice(pd.date_range(datetime.datetime(2013,1,1),datetime.datetime(2013,1,3))) for i in range(24)],
    'D' : np.random.randn(24),
    'E' : np.random.randint(2,10,24),
    'F' : [np.random.choice(['rand_1', 'rand_2', 'rand_4', 'rand_6']) for i in range(24)],
})
df_to_org(df)
fig = px.line(df[["E"]], template="plotly_dark")
render_plotly(fig)