Skip to content

Instantly share code, notes, and snippets.

@fredmajor
Last active April 15, 2018 18:04
Show Gist options
  • Save fredmajor/d489a042bb46303f3f38ffc9c03e6a2c to your computer and use it in GitHub Desktop.
Save fredmajor/d489a042bb46303f3f38ffc9c03e6a2c to your computer and use it in GitHub Desktop.
def print_df_markdown(df, index=True):
"""
This prints a pandas dataframe in a form ready to be used as a markdown table.
Simply print and copy-paste to your hot, new blog post.
"""
print()
cols = list(df)
if index:
cols = ['Index'] + cols
header = ' | '.join(cols)
col_divider = ['---' for c in cols]
div_line = ' | '.join(col_divider)
print(header)
print(div_line)
for row in df.itertuples(index=index):
line_str = ' | '.join(map(str, row))
print(line_str)
"""
example output:
Index | type1 | type2
--- | --- | ---
2018-04-12 00:00:00 | 1.0 | 0.0
2018-04-13 00:00:00 | 0.0 | 1.0
2018-04-14 00:00:00 | 0.0 | 0.0
2018-04-15 00:00:00 | 0.0 | 0.0
2018-04-16 00:00:00 | 1.0 | 3.0
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment