Skip to content

Instantly share code, notes, and snippets.

@WindfallLabs
Created September 6, 2019 17:15
Show Gist options
  • Save WindfallLabs/4f0abe566503e3a5b349aa6a1ba7ef5f to your computer and use it in GitHub Desktop.
Save WindfallLabs/4f0abe566503e3a5b349aa6a1ba7ef5f to your computer and use it in GitHub Desktop.
Convert DataFrame to Markdown (string)
import re
import pandas as pd
def df_to_markdown(df, index=False):
"""Converts a pandas DataFrame to a Markdown string.
Args:
df (DataFrame): dataframe to convert
index (bool): optionally, keep the DataFrame index (default False)
"""
# Set list index
ix = 1
if index:
ix = 0
# Get Dataframe rows as lists
array = [list(i)[ix:] for i in df.itertuples()]
# Get column names
cols = df.columns.tolist()
# Insert index column name if included
if index:
cols.insert(0, "ix")
# Add column names to beginning of array
array.insert(0, cols)
# Create list of formatted rows
queue = []
for row in array:
row_strs = []
for value in row:
value = str(value)
# Buffer value with spaces
new_val = value.ljust(len(value)+1).rjust(len(value)+2)
row_strs.append(str(new_val))
queue.append("|" + "|".join(row_strs) + "|")
# Insert the formatting/centering line
queue.insert(1, "| {} |".format(" | ".join([":--:"]*len(array[0]))))
# Return markdown
return "\n".join(queue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment