Knitpy Overview
Knitpy Overview
Knitpy Overview
python
Jan Schulz
12.03.2015
This is a port of knitr (http://yihui.name/knitr/) and rmarkdown
(http://rmarkdown.rstudio.com/) to python.
For a complete description of the code format see
http://rmarkdown.rstudio.com/ and replace {r...} by {python ...} and of
course use python code blocks
Examples
Here are some examples:
print("Execute some code chunk and show the result")
## Execute some code chunk and show the result
Codechunks which contain lines without output (e.g. assign the result
or comments) will be shown in the same code block:
# A comment
text = "All code in the same code block until some output is produced..."
more_text = "...and some more."
print(text)
## All code in the same code block until some output is produced...
print(more_text)
## ...and some more.
Inline code
You can also include code inline: m=2 (expected: m=2)
strong text
It even handles pandas.DataFrames (be aware that not all formatting
can be converted into all output formats):
import pandas as pd
pd.set_option("display.width", 200)
s = """This is longer text"""
df = pd.DataFrame({"a":[1,2,3,4,5],"b":[s,"b","c",s,"e"]})
df
0
1
2
3
4
pandas.DataFrame can be represented as text/plain or text/html, but will
default to the html version. To force plain text, use either print(df) or set
the right pandas option:
pd.set_option("display.notebook_repr_html", False)
df
##
##
##
##
##
##
0
1
2
3
4
a
b
1 This is longer text
2
b
3
c
4 This is longer text
5
e
You can also use package like tabulate together with results="asis" or
by wrapping it with the appropriate display class:
from tabulate import tabulate
from IPython.core.display import Markdown
# either print and use `results="asis"`
print(tabulate(df, list(df.columns), tablefmt="simple"))
0
1
2
3
4
# or use the IPython display framework to publish markdown
Markdown(tabulate(df, list(df.columns), tablefmt="simple"))
0
1
2
3
4
Note that the second version (wrapping it in Markdown) is preferred, as
this marks the output with the right mimetype and therefore can be
convertedif thats neededto something which the output format
understands!
Unfortunately, html tables have to be tweaked for the final output
format as e.g. too width tables spill over the page margin in PDF.
Error handling
Errors in code are shown with a bold error text:
import sys
print(sys.not_available)