How to install package and display pandas dataframe inside the tab?

import ipywidgets as widgets
tab = widgets.Tab()
import subprocess
import sys

def install(package):
“”“Install a package using pip.”“”
subprocess.check_call([sys.executable, ‘-m’, ‘pip’, ‘install’, package])

def main():
# List of packages to install
packages = [
‘numpy’,
‘pandas’
]

for package in packages:
    try:
        print(f"Installing {package}...")
        install(package)
        return(f"{package} installed successfully.")
    except Exception as e:
        return(f"Failed to install {package}. Error: {e}")
    import pandas as pd
    df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
               'mask': ['red', 'purple'],
               'weapon': ['sai', 'bo staff']})
    return df

tab.children = [widgets.HTML(main())]
tab.titles = [‘tab1’]
display(tab)

Just looking at your title - is that what you are asking for?

import ipywidgets as widgets
import pandas as pd

df = pd.DataFrame({'a': ['a', 'b', 'c'], 'b': [1, 2, 3]})

tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4']
children = [widgets.Output() for name in tab_contents]
tab = widgets.Tab()
tab.children = children
tab.titles = [str(i) for i in range(len(children))]

# Here you are showing the dataframe in the output which resides in the tab
with children[0]:
    display(df)

tab

2 Likes

I think it’s working because pandas package is already installed on jupyter notebook.What if the package is not installed?

Ah - I did not take your title at face value - I thought it was about getting a package installed (separate process), then showing the dataframe in a tab widget.

I will have to defer to someone with more knowledge, since I generally have to restart the kernel to load new packages installed - I am not aware of how to do that without reloading the kernel.

This part is like you are taking pyscript configuration code and expecting it to work in Jupyter? I’m not sure why you’d do that? As Afonit references, installing packages is a separate process that you’d do.

You’d follow standard Python and Jupyter practices to install packages in the environment where your kernel is running. One of the most straightforward options is to add a new cell above the ipywidgets code that afonit provided. In that new cell you’d enter the following:

%pip install pandas numpy

Then run that cell. That magic symbol in combination with the pip install will help insure it installs into the environment where the kernel is running. (That install command will work in JupyterLite, too.) Then if the install goes successfully, restart the kernel and you should be able to run the code import pandas as pd and see it imported without error. Similar with import numpy as np. Ipywidgets makes more changes in more places and so it isn’t as simple to install that way. (Sometimes it will work that way if you add in additional hard refresh of your browser page. I also recommend restarting both Jupyter and your browser, maybe even the entire machine, plus the hard refresh on the browser page after the ipywidgets install step.) You didn’t ask about that one and so hopefully that means you already have that covered. Once you have those installed afonit’s code should work.

See more about the modern %pip install command here.

1 Like

I want to know if it is possible with one cell.I want to install package with in the tab.Like in pycafe you just mention package in a tab and you can make use of them in other tabs.

Did you try it?

I just ran the following in one cell and it was fine.

%pip install pandas
import pandas as pd

(You can test in yourself by launching JupyterLab with an ipykernel here and trying the import statement first to verify it isn’t installed.)

Point is that it is not reliable for all packages, and so it is not the standard supported way.

I think you may be dragging out an XY Problem here?
Let me ask why would you want to do that with Jupyter? Why are you limited in cells? Why can’t you install it in one of the many ways you can install things in the environment so that it is pre-installed and not needed to installed in the same cell?

Py.cafe is awesome but it is designed very differently than Jupyter and the typical ipykernel.
JupyterLite is a bit closer in relation to it. In particular the jupyterlite-xeus-python allows you to pre-install packages, see here. And with the pyodide kernel you can do dynamic installing at this time, (I believe something along the line is in works for jupyterlite-xeus-python). For example, go to here, and click on the yellow ‘Try lite now badge’. Then when that comes up start a new notebook with the ‘Python (Pyodide)’ kernel. Then put a cell import ipywidgets as widgets and it will say not installed with the error ModuleNotFoundError: No module named 'ipywidgets'. And so now open yet another new notebook with the ‘Python (Pyodide)’ kernel and put the following in the first cell, based on Afonit’s code and adding the install command magic command (that as I said earlier, also works in JupyterLite):

%pip install ipywidgets
import ipywidgets as widgets
import pandas as pd

df = pd.DataFrame({'a': ['a', 'b', 'c'], 'b': [1, 2, 3]})

tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4']
children = [widgets.Output() for name in tab_contents]
tab = widgets.Tab()
tab.children = children
tab.titles = [str(i) for i in range(len(children))]

# Here you are showing the dataframe in the output which resides in the tab
with children[0]:
    display(df)

tab

It works on my machine in Chrome browser and so I hope it works on yours.

Finally, even closer to Py.cafe in some ways is Voici, that is JupyterLite combined with Voila for apps/dashboards based on Jupyter .ipynb files, but last I knew it is still in very early development. You can try it by clicking here. That is the demo you can also access from the yellow badge here on the documentation page. One of the hurdles I found to developing with Voici as lack of easy preview like you get with Voila; however, the end of the post from the end of 2023 says that is in the works.

Yes the code works. I was not sure if I install it outside I can make use of them inside of the tabs.I think its going to work with Voila deployment but not with Voici.

1 Like

In the case of typical ipykernel/Jupyter (as opposed to WASM/JupyterLite-stuff, for now), as long as you install into the environment utilized by the running kernelm the packages can be imported and used in Jupyter. Ipywidgets tabs would not be separate in any way.