Print Variable In Jupyter Notebook Markdown Cell Python - python

Can I print the value of a variable in Markdown Cell Jupyter Notebook?
Tried Code:
value = 5.3
Markdown cell --> Value is {{ value }}
I want that the Markdown cell should display the value of variable
SCREENSHOT

#nilansh bansal's answer works great for Jupyter Notebooks. Unfortunately, it doesn't work for JupyterLab because the plugin is no longer supported (as is the case for all nbextension plugins). Since JupyterLab gains popularity, I wanted to complement the answers so far because it took me quite some time to find a solution. This is because until now there is no plugin compatible with JupyterLab. I have found the following solution for myself by combining this and this SO answers:
from IPython.display import Markdown as md
# Instead of setting the cell to Markdown, create Markdown from withnin a code cell!
# We can just use python variable replacement syntax to make the text dynamic
n = 10
md("The data consists of {} observations. Bla, Bla, ....".format(n))
Alternatively, the last line can be simplified as suggested by #Igor Fobia for Python >3.6:
md(f"The data consists of {n} observations. Bla, Bla, ....")
This leads to the desired output. However, it has the huge disadvantage that the code cell will still be visible when exporting the NB. This can be solved though:
Add a tag to the code cell, i.e. name it "hide"
Configure nbconvert to ignore the tagged cells, e.g. by adding this c.TagRemovePreprocessor.remove_input_tags = {"hide"} to your ~/.jupyter/jupyter_notebook_config.py config file
I have written a detailed blog-post about how I implemented this solution for publishing Notebooks on my blog. If you use JupyterLab < 2.0, you could install the jupyterlab-celltags plugin for JupyterLab to simplify the cell tagging.

So After going through all the links I was able to resolve the problem by referring to nbextension jupyter notebook docs : https://github.com/ipython-contrib/jupyter_contrib_nbextensions
Steps Taken:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable python-markdown/main
After the above commands started a jupyter notebook and to print the value of a variable in the markdown cells works like charm!
You just have to use {{ ac_score }} within a markdown cell.
Screenshot
Thanks!

You can overwrite %%markdown IPython magic to substitute variables from the global environment:
from IPython.display import Markdown
from IPython.core.magic import register_cell_magic
#register_cell_magic
def markdown(line, cell):
return Markdown(cell.format(**globals()))
This has the advantage of allowing for Markdown linting when used with JupyterLab-LSP.
If developing a documentation with nbsphinx you can hide the input (source of the cell) by setting {"hide_input": true} in cell metadata:
(note the Jupyter[Lab] and LSP underlined as those are not in the English dictionary - linting works!)
which results in smooth docs like this:
For a better experience when in JupyterLab you can always collapse the input cell by clicking on the blue bar to the left of it (visible when you hover over the cell).

Related

Force Jupyter to print and not display

I am using Jupyter notebooks in Visual Studio Code to present lab sessions for my Python programming course, albeit I am recommending students to work with .py files for themselves and their submissions. Ideally I would like the output of my Python cells to be identical to a Python console, and not pretty-printed by display.
I have already added
"jupyter.runStartupCommands": [
"from IPython.core.interactiveshell import InteractiveShell",
"InteractiveShell.ast_node_interactivity = 'all'"
]
to settings.json to ensure I get all output but it is still passed to display. However, in a Python console, running int shows the representation <class 'int'>, whereas in the notebook it just shows int. Is there a way to force the Python cells to print and not display, so that the output is identical?

Notebook in VSCode displays no output for some stored variables

Consider the following code:
import pandas as pd
import os
csv = """Country,Total Cases,New Cases,Total Deaths,New Deaths,Recovered,Serious
China,74187,1751,2006,138,14796,12017
Diamond Princess,621,79,,,17,20
Singapore,81,,,,29,4
Japan,80,6,1,,20,4
Hong Kong,63,1,2,1,5,6
S. Korea,51,20,,,16,
Thailand,35,,,,17,2
USA,29,,,,3,
Taiwan,23,1,1,,2,
Malaysia,22,,,,15,
Vietnam,16,,,,14,
Germany,16,,,,9,
Australia,15,,,,10,
France,12,,1,,7,
Macao,10,,,,5,
U.A.E.,9,,,,3,1
U.K.,9,,,,8,
Canada,8,,,,1,
Philippines,3,,1,,2,
Italy,3,,,,,2
India,3,,,,3,
Russia,2,,,,2,
Spain,2,,,,2,
Nepal,1,,,,1,
Belgium,1,,,,1,
Sri Lanka,1,,,,1,
Finland,1,,,,1,
Egypt,1,,,,,
Cambodia,1,,,,1,
Sweden,1,,,,,"""
with open("data/covid.csv", "w") as file:
file.write(csv)
df = pd.read_csv("data/covid.csv").fillna(0).astype(dtype = int, errors='ignore')\
.sort_values(by='Total Cases', ascending=False)
latest = df.to_dict('list')
some_var = latest.keys()
print(latest.keys()) # It's a notebook. Printing or calling a variable does not matter.
latest.keys()
Please see the attached image to see the issue
It works in a jupyter notebook on conda and if I run it via a normal python file. Which highlights that the issue lies with how VSCode displays notebook outputs
As you can see, VSCode does not display some outputs after running a cell, but does display others after running a cell.
If I try this in a conda environment, it works just fine:
Any suggestions for why this issue only happens in VSCode & How I might go about fixing it? Is it a kernel thing?
This issue was caused by an extension within vscode called Leaflet Map.
It changed the default renderer for notebook cells in vscode.
If anyone else has issues with VSCode outputs in future, you can click the elipsis on the output cell -> Click Change Presentation & ensure you're using an up to date renderer:

Using rpy2 in jupyter notebook but there is no output. Error in withVisible({ : object 'returns' not found

the screenshot for jupyternotebook
I've successfully installed ryp2 using wheel. I'm using Python 3.7.6 and rpy2 2.9.5.
I can get the output from jupter notebook when running python code but it doesn't work when using R magic. I tried to see if I can really use R by installing 'ggplot2' and it worked with installation bar poped out.
However, I cannot get any output when I use R magic.
Errors will come out like this. The error is so weird Error in withVisible({ : object 'returns' not found. returns is a python dataframe and was not converted to r object.
Error in withVisible({
Other error like below. Error in eval(predvars, data, env) : object 'p' not found. Neither p nor q is initialized.
Error in eval(predvars, data, env)
Anyone encountered the same problem?
Thank you very much in advance!
FYI:
packages version
This is only a partial answer; I do not know why you cannot see output of 1 for:
%%R
a = 1
a
but I know that the "errors" you see are there because the variables are indeed not defined - you still need to tell rpy2 to import (-i for input) or export (-o for output) variables between R and Python namespaces, this does not happen automatically (if it did you would end up with each object taking up twice as much space!). This is done using:
%R -i variable_to_import_from_python
And
%R -o variable_to_export_to_python
(or equivalently using %%R). It means that in your examples in order to Python print(a) you first need to:
%%R -o a
a = 1
a
And to have Python variable b, say b = 1 in R you would need to:
%%R -i b
cat(b)
Please read the documentation for using rpy2 in notebooks (magics are covered near the end) and the documentation of RMagic, as it is already explained in there.
I hope you will get an answer on the non-functioning R output soon. If you do not get one in the next few days please consider opening a bug report on rpy2 GitHub.

Notebook validation failed Jupyter

This is not a duplicate of Notebook Validation Failed.
I have a Jupyter ntb which was working well until recently. Whatever I do, I am getting those kind of errors which are changing (I'm attaching a few examples) and it does not matter what I do with the ntb (I tried restarting kernel, restarting Jupyter). Also, it is happening ONLY in this ntb, not in others even if run at the same time from the same session. I tried to search but could not find anything. What I get in the Jupyter is:
There are many of those, similar but different:
The save operation succeeded, but the notebook does not appear to be valid. The validation error was:
Notebook validation failed: Non-unique cell id 'geological-poker' detected. Corrected to 'front-hampshire'.:
"<UNKNOWN>"
or others:
Notebook validation failed: Non-unique cell id 'medieval-nebraska' detected. Corrected to 'stock-eating'.:
"<UNKNOWN>"
Notebook validation failed: Non-unique cell id 'intense-award' detected. Corrected to 'blocked-garage'.:
"<UNKNOWN>"
And what I get in the terminal is:
Notebook JSON is invalid: Non-unique cell id 'medieval-nebraska' detected. Corrected to 'convinced-vacation'.
or
Notebook JSON is invalid: Non-unique cell id 'medieval-nebraska' detected. Corrected to 'described-commerce'.
Notebook JSON is invalid: Non-unique cell id 'meaning-victoria' detected. Corrected to 'occasional-numbers'.
Notebook JSON is invalid: Non-unique cell id 'eastern-buyer' detected. Corrected to 'english-benchmark'.
Any idea what's going on and how to fix it?
Update:
It got fixed somehow for a while but then it started doing the same again I still do not get what it was and how it got fixed and ruined again... One fix is to make a copy of the ntb and then discard the old one.
Update 9.10.21:
It looks that this is no more a problem for python v3.8.11. I have not managed to reproduce the issue since updating all packages so probably the easiest fix now is to update. I have:
jupyter core : 4.7.1
jupyter-notebook : 6.4.3
ipython : 7.26.0
ipykernel : 6.2.0
I also happened to find another solution that worked:
First select all the cells in the Jupyter Notebook, then press the "cut/scissors" button (don't panic, at this point your Notebook will be empty), and finally press the "paste" button.
This is from https://github.com/jupyter/notebook/issues/6001#issuecomment-959828688.
I have the same issue and after reading about it, it seems the cause is copy/pasting cells from other notebooks that were created in other sessions. I haven't found a way to fix it, but at least you can prevent it from happening by copying the content of the cells and not the cells themselves.
Simple Answer
STEP 1: Cut all the cells in the Jupyter-notebook using scissor option as shown.
STEP 2: Save the notebook now, and paste back the cells cut in the previous step using paste option as shown.
STEP 3: Save again and your bug should be fixed now! Hurry, Happy coding.
Code to resave a notebook with the cell name issue resolved:
import nbformat as nbf
from glob import glob
import uuid
def get_cell_id(id_length=8):
return uuid.uuid4().hex[:id_length]
# -- SETUP
nb_name = 'my_notebook'
# -- MAIN
# grab notebook
notebooks = list(filter(lambda x: nb_name in x, glob("./*.ipynb", recursive=True)))
# iterate over notebooks
for ipath in sorted(notebooks):
# load notebook
ntbk = nbf.read(ipath, nbf.NO_CONVERT)
cell_ids = []
for cell in ntbk.cells:
cell_ids.append(cell['id'])
# reset cell ids if there are duplicates
if not len(cell_ids) == len(set(cell_ids)):
for cell in ntbk.cells:
cell['id'] = get_cell_id()
nbf.write(ntbk, ipath)
Source: https://github.com/jupyter/notebook/issues/6001#issuecomment-856303981

Using Hydrogen, how do I save they python script with output included like a jupyter notebook?

I'm new to Atom and Jupyter. I've only installed Hydrogen and I'm testing on a simple script. I can make some data and, shift+Enter shows the plot inline! I'd like to save the file w/ the output blocks I see in the Atom+Hydrogen GUI. I've seen other Jupyter notebooks like this. Can I do it and how?
You can use Pandoctools for this. It can export hydrogen *.py / *.md documents to any Pandoc output format or to Jupyter notebook.
For example you can create and register Jupyter kernel. For example is can be named "nn". That should be the same kernel that you selected in Atom/Hydrogen. Then add hat to the Python file, split Hydrogen to cells, provide settings and set Markdown cells (commented metadata line would export to ipynb that can be opened in nteract native app):
"""
---
kernels-map:
py: nn
jupyter:
kernelspec:
display_name: nn
language: python
name: nn
pandoctools:
out: "*.pdf"
# out: "*.ipynb"
...
# Markdown section title 1
Some **static** Markdown text.
"""
# %% {echo=False}
import IPython.display as ds
import math
import sugartex as stex
# %% {markdown}
"""
# Markdown section title 2
The quick brown Fox jumps over the lazy dog.
"""
# %%
ds.Markdown(stex.pre(f'''
Some **dynamic** Markdown text with SugarTeX formula: ˎα^˱{math.pi:1.3f}˲ˎ.
It works because of the `Markdown` display option and `sugartex` Pandoc filter.
Acually `stex.pre` is redundant here but it is needed when the text is imported
or read from somewhere instead of being written in the same document.
'''))
Then convert the file via pandoctools: drag and drop file to pandoctools shortcut/executable or "open with" pandoctools executable.
Also see:
introduction article: convenient and easily tweakable Atom+Markdown+Pandoc+Jupyter experience,
examples of input to output conversion that have cross-references!
how to use Pandoctools and it's CLI,
how to use Knitty that collects Jupyter outputs and change it's settings.

Categories