Skip to content

Instantly share code, notes, and snippets.

@abubelinha
Forked from jplsightm/df_to_markdown.py
Last active November 7, 2021 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abubelinha/560e386ee3c65db23f71606cfafba596 to your computer and use it in GitHub Desktop.
Save abubelinha/560e386ee3c65db23f71606cfafba596 to your computer and use it in GitHub Desktop.
Convert a Pandas Dataframe to Markdown
import pandas as pd
from tabulate import tabulate
def pandas_df_to_markdown_table(df):
# Dependent upon ipython
# shamelessly stolen from https://stackoverflow.com/questions/33181846/programmatically-convert-pandas-dataframe-to-markdown-table
from IPython.display import Markdown, display
fmt = ['---' for i in range(len(df.columns))]
df_fmt = pd.DataFrame([fmt], columns=df.columns)
df_formatted = pd.concat([df_fmt, df])
#display(Markdown(df_formatted.to_csv(sep="|", index=False)))
return Markdown(df_formatted.to_csv(sep="|", index=False))
# return df_formatted
def df_to_markdown(df, y_index=False):
blob = tabulate(df, headers='keys', tablefmt='pipe')
if not y_index:
# Remove the index with some creative splicing and iteration
to_return = '\n'.join(['| {}'.format(row.split('|', 2)[-1]) for row in blob.split('\n')])
else:
to_return = blob
# if you don't like the left/right column alignments generated by tabulate:
to_return = to_return.replace("----:","-----").replace(":----","-----")
return to_return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment