A similar question is as here - Print Variable In Jupyter Notebook Markdown Cell Python - but they were having issues with the compiling. My issue is in what Python code I should be using so that the variable is viewable when the html is compiled.
I have a dataset df4 with which I want to reference inline in the markdown of my jupyter notebook.
df4['amount'].sum()
works fine. But (all on the same line in Markdown)
df4.groupby(['customer_name'])['amount_due'].sum().reset_index() \
.query('amount_due > 0')['amount_due'] \
.sum()
returns the error **SyntaxError**: only a single expression is allowed ()
I could of course define all the variables I need in a Python cell above the Markdown cell in Jupyter Notebook and then refer to them within the Markdown cell only by name. E.g. "The total amount is {{x}}"
.
But since there is this functionality (and also I have already compiled this report in R Markdown with inline R code) - I wanted to use it.
This is an example of what I am trying to achieve within jupyter notebook:
# Python3 cell
import pandas as pd
dt = {'customer_name': ['a','a','b','b','c'], 'amount': [-1,-1,1,1,1000]}
df4 = pd.DataFrame(data = dt)
df4
#### Markdown cell
This is a large amount : {{df4['amount'].sum()}} - let me explain further...
Output: This is a large amount : 1000 - let me explain further...
#### Markdown cell
This is a *larger* amount : {{df4.groupby(['customer_name'])['amount'].sum().reset_index().query('amount > 0')['amount'].sum()}} - let me explain further...
Expected: This is a large amount : 1002 - let me explain further...
When running the last cell the output is **SyntaxError**: only a single expression is allowed ()
.
The problem is with the ">" operator. It seems that markdown does not like the use of this character. Related issue on GitHub: Python-markdown syntax error if contains < or >.