How can remove markdown table alignment when I use pandas.to_markdown

Question:

Thank you for your consideration.

Summarize the problem

When I transfer talbe from excel to markdown I use pandas library.

  1. Copy table in excel to clipboard.
  2. Make a dataframe by pd.read_clipboard
  3. Make str(markdown table) by pd.to_markdown

Str from pd.to_markdown alwasy applied alignment.

But I want to remove alignment in markdown table when I make str by pd.to_markdown.

here are some example.

text from clipboard

post_it width   height
653 51  38
654 76  76
656 76  51
657 102 76
import pandas as pd
df=pd.read_clipboard()
markdown_table=df.to_markdown(index=False)
print(df)
   post_it  width  height
0      653     51      38
1      654     76      76
2      656     76      51
3      657    102      76
print(markdown_table)

What I recived from pd.to_markdown

|   post_it |   width |   height |
|----------:|--------:|---------:|
|       653 |      51 |       38 |
|       654 |      76 |       76 |
|       656 |      76 |       51 |
|       657 |     102 |       76 |

What I want data from pd.to_markdown

There is no colon symbol 2nd line

|   post_it |   width |   height |
|-----------|---------|----------|
|       653 |      51 |       38 |
|       654 |      76 |       76 |
|       656 |      76 |       51 |
|       657 |     102 |       76 |
Asked By: student

||

Answers:

The to_markdown() method has a tablefmt parameter.

This looks like what you want:

print(df.to_markdown(tablefmt="github", index=False))

# Output

|   post_it |   width |   height |
|-----------|---------|----------|
|       653 |      51 |       38 |
|       654 |      76 |       76 |
|       656 |      76 |       51 |
|       657 |     102 |       76 |

There are many formats to choose from if this isn’t what you want. They’re listed in the docs: https://github.com/astanin/python-tabulate

Answered By: Ray
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.