Home > other >  Converting multi-indexed dataframe to markdown
Converting multi-indexed dataframe to markdown

Time:10-05

Currently I have multi-indexed dataframe as below.

enter image description here

I wanted it's markdown to look like this

|       |          |   col | 
|-------|----------|-------|
| April |    1     |     6 |
| April |    2     |     7 |
| August|    1     |    14 |

But what I get after df.to_markdown(tablefmt='github') is

|                  |   col |
|------------------|-------|
| ('April', 1)     |     6 |
| ('April', 2)     |     7 |
| ('August', 1)    |    14 |

Can anyone tell me how to do get the markdown as I want.

CodePudding user response:

You need first to flatten the multi index with pandas.DataFrame.reset_index then set index=False in pandas.DataFrame.to_markdown :

out= (
        df.reset_index()
          .rename(columns={'idx1': '', 'idx2': ''})
          .to_markdown(tablefmt='github', index=False)
      )

# Output:

print(out)

|          |    |   col |
|----------|----|-------|
| April    |  1 |     6 |
| April    |  2 |     7 |
| August   |  1 |    14 |
| August   |  2 |    15 |
| December |  1 |    22 |
| December |  2 |    23 |
| February |  1 |     2 |
| February |  2 |     3 |
| January  |  1 |     0 |
  • Related