Programmatically convert pandas dataframe to markdown table
Improving the answer further, for use in IPython Notebook:
def pandas_df_to_markdown_table(df): 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)))pandas_df_to_markdown_table(infodf)
Or use tabulate:
pip install tabulate
Examples of use are in the documentation.
I recommend python-tabulate library for generating ascii-tables. The library supports pandas.DataFrame
as well.
Here is how to use it:
from pandas import DataFramefrom tabulate import tabulatedf = DataFrame({ "weekday": ["monday", "thursday", "wednesday"], "temperature": [20, 30, 25], "precipitation": [100, 200, 150],}).set_index("weekday")print(tabulate(df, tablefmt="pipe", headers="keys"))
Output:
| weekday | temperature | precipitation ||:----------|--------------:|----------------:|| monday | 20 | 100 || thursday | 30 | 200 || wednesday | 25 | 150 |
Pandas 1.0 was released 29 january 2020 and supports markdown conversion, so you can now do this directly!
Example taken from the docs:
df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])print(df.to_markdown())
| | A | B ||:---|----:|----:|| a | 1 | 1 || a | 2 | 2 || b | 3 | 3 |
Or without the index:
print(df.to_markdown(index=False)) # use 'showindex' for pandas < 1.1
| A | B ||----:|----:|| 1 | 1 || 2 | 2 || 3 | 3 |