Back to TILs.

Calmcode TIL

Pandas to Markdown logoPandas to Markdown

Sometimes you want to have a neat table appear in a markdown file, such that a neat table can render. A table like below.

Date MSFT KLM ING MOS
2000-01-20 34.35 0.35 14.06 14.09
2000-01-21 34.33 0.35 13.92 13.79
2000-01-24 33.3 0.35 13.56 13.79
2000-01-25 32.4 0.35 13.22 13.45
2000-01-26 32.86 0.35 13.33 13.59
2000-01-27 32.05 0.35 13.28 13.25
2000-01-28 31.48 0.35 13.09 13
2000-01-31 31.32 0.35 12.79 13.3
2000-02-01 31.6 0.35 12.78 13.59
2000-02-02 32.86 0.35 12.7 13.45

To render such a table, you need to construct a table in the right syntax. The markdown for this table looks like this:

| Date       |   MSFT |   KLM |   ING |   MOS |
|:-----------|-------:|------:|------:|------:|
| 2000-01-20 |  34.35 |  0.35 | 14.06 | 14.09 |
| 2000-01-21 |  34.33 |  0.35 | 13.92 | 13.79 |
| 2000-01-24 |  33.3  |  0.35 | 13.56 | 13.79 |
| 2000-01-25 |  32.4  |  0.35 | 13.22 | 13.45 |
| 2000-01-26 |  32.86 |  0.35 | 13.33 | 13.59 |
| 2000-01-27 |  32.05 |  0.35 | 13.28 | 13.25 |
| 2000-01-28 |  31.48 |  0.35 | 13.09 | 13    |
| 2000-01-31 |  31.32 |  0.35 | 12.79 | 13.3  |
| 2000-02-01 |  31.6  |  0.35 | 12.78 | 13.59 |
| 2000-02-02 |  32.86 |  0.35 | 12.7  | 13.45 |

Making such a table manually is a lot of tedious work though. Thankfully, you can easily convert a pandas DataFrame such that you can automatically generate the table.

To generate this table, you'll need to make sure that tabulate is installed first.

python -m pip install tabulate

Once that is installed you can generate the table shown above via:

import pandas as pd

# Load the data
df = pd.read_csv("https://calmcode.io/datasets/stocks.csv")

# Generate the markdown table
print(df.head(10).to_markdown(index=False))

Back to main.