Skip to content

Instantly share code, notes, and snippets.

@rgerkin
Created February 15, 2019 22:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgerkin/af5b27a0e30531c30f2bf628aa41a553 to your computer and use it in GitHub Desktop.
Save rgerkin/af5b27a0e30531c30f2bf628aa41a553 to your computer and use it in GitHub Desktop.
This takes a pandas dataframe and renders the Markdown in the output of a Jupyter code cell
#!pip install --user tabulate # Install the tabulate package
from tabulate import tabulate
import numpy as np
import pandas as pd
import IPython.display as d
# Some random data
data = np.random.rand(10,4)
# Columns A, B, C, D
columns = [chr(x) for x in range(65,69)]
# Create the dataframe
df = pd.DataFrame(data=data,
columns=columns)
# Optionally give the dataframe's index a name
#df.index.name = "my_index"
# Create the markdown string
md = tabulate(df, headers='keys', tablefmt='pipe')
# Fix the markdown string; it will not render with an empty first table cell,
# so if the dataframe's index has no name, just place an 'x' there.
md = md.replace('| |','| %s |' % (df.index.name if df.index.name else 'x'))
# Create the Markdown object
result = d.Markdown(md)
# Display the markdown object (in a Jupyter code cell)
result
@russelljjarvis
Copy link

This has a lot of utility for writing papers in Markdown.

@aborruso
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment