Pandas Printing

Author

Christophe Dervieux

Published

July 19, 2023

library(reticulate)
use_virtualenv("r-reticulate", required = TRUE)
py_install(c("pandas", "IPython", "tabulate"))
Using virtual environment "C:/Users/chris/Documents/.virtualenvs/r-reticulate" ...
+ "C:/Users/chris/Documents/.virtualenvs/r-reticulate/Scripts/python.exe" -m pip install --upgrade --no-user "pandas" "IPython" "tabulate"
import pandas as pd

data = {
  'size': [1., 1.5, 1],
  'weight': [3, 5, 2.5]
}

df = pd.DataFrame(data, index = ['cat', 'dog', 'koala'])

Default render

df
       size  weight
cat     1.0     3.0
dog     1.5     5.0
koala   1.0     2.5

Try HTML

Some quote are still there preventing correct printing

df.to_html()
'<table border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th></th>\n      <th>size</th>\n      <th>weight</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>cat</th>\n      <td>1.0</td>\n      <td>3.0</td>\n    </tr>\n    <tr>\n      <th>dog</th>\n      <td>1.5</td>\n      <td>5.0</td>\n    </tr>\n    <tr>\n      <th>koala</th>\n      <td>1.0</td>\n      <td>2.5</td>\n    </tr>\n  </tbody>\n</table>'
df.to_html()
size weight
cat 1.0 3.0
dog 1.5 5.0
koala 1.0 2.5

So it requires some special processing

df_html = df.to_html()
cat(py$df_html)
size weight
cat 1.0 3.0
dog 1.5 5.0
koala 1.0 2.5

Using IPython Display helps

from IPython.display import HTML
HTML(df.to_html())
size weight
cat 1.0 3.0
dog 1.5 5.0
koala 1.0 2.5

Improve stylings using Bootstrap class

df_html = df.to_html(classes = ["table", "table_condensed"])
cat(py$df_html)
size weight
cat 1.0 3.0
dog 1.5 5.0
koala 1.0 2.5
HTML(df.to_html(classes = ["table", "table_condensed"]))
size weight
cat 1.0 3.0
dog 1.5 5.0
koala 1.0 2.5

Try Markdown

Still quoting, so it requires some special printing

df.to_markdown()
'|       |   size |   weight |\n|:------|-------:|---------:|\n| cat   |    1   |      3   |\n| dog   |    1.5 |      5   |\n| koala |    1   |      2.5 |'
df.to_markdown()

‘| | size | weight ||:——|——-:|———:|| cat | 1 | 3 || dog | 1.5 | 5 || koala | 1 | 2.5 |’

df_markdown = df.to_markdown()
cat(py$df_markdown)
size weight
cat 1 3
dog 1.5 5
koala 1 2.5

Using IPython Display helps

from IPython.display import Markdown
Markdown(df.to_markdown())
size weight
cat 1 3
dog 1.5 5
koala 1 2.5