How to create multiple instances of object and display methods

Hi @yobae

Welcome to the community :+1:

You can use a Selector parameter to keep track of your datasets and the current dataset.

from io import StringIO

import pandas as pd
import panel as pn
import param

pn.extension("tabulator", sizing_mode="stretch_width")

ACCENT_COLOR="#0072B5"

class Dataset(param.Parameterized):
    value = param.DataFrame()

class FiberGui(param.Parameterized):
    new_dataset_input = param.ClassSelector(class_=pn.widgets.FileInput, constant=True)
    dataset=param.Selector()

    def __init__(self, **params):
        params["new_dataset_input"]=pn.widgets.FileInput(accept = '.csv')
        super().__init__(**params)
        self.param.dataset.objects=[]


    @pn.depends("new_dataset_input.value", watch = True)
    def _parse_new_data_set(self):
        value = self.new_dataset_input.value
        if not value:
            return

        string_io = StringIO(value.decode("utf8"))
        dataset = Dataset(value=pd.read_csv(string_io), name=self.new_dataset_input.filename)
        existing_datasets = self.param.dataset.objects
        self.param.dataset.objects=[*existing_datasets, dataset]
        self.dataset = dataset

    @pn.depends("dataset")
    def output(self):
        if self.dataset:
            return pn.widgets.Tabulator(self.dataset.value.head(100), theme="fast", height=800, pagination="remote", page_size=25)
        else:
            return "No Datasets Loaded"

gui = FiberGui()

template = pn.template.FastListTemplate(
    site = "Awesome Panel", title = 'Fiber Photometry App with File Upload',
    sidebar = ["**Upload a new dataset** here", gui.new_dataset_input, pn.Param(gui, parameters=["dataset"], show_name=False)],
    main = [pn.panel(gui.output, loading_indicator=True)],
    accent_base_color=ACCENT_COLOR, header_background=ACCENT_COLOR
)
template.servable()

If you like this example please share on twitter https://twitter.com/MarcSkovMadsen/status/1469588373912395776?s=20 or Linked In Panel on LinkedIn: #dataviz #python #datascience. Thanks

2 Likes