Created
February 15, 2019 22:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has a lot of utility for writing papers in Markdown.