In this article, you’ll learn how to save Pandas DataFrame as a markdown file. You have to follow these two given steps.
Step 1:
First, install the tabulate library using this code.
pip install tabulate
Step 2: Save DataFrame as a Markdown file
This will save the Pandas DataFrame to the same folder in which your code file is opened.
# Import the pandas library as pd import pandas as pd # Create a DataFrame df = pd.DataFrame({'A': ['5', '10', '15', '20'], 'B': ['25', '50', '60', '90']}) # Display the Markdown table print(df.to_markdown()) # Save the DataFrame to a Markdown file df.to_markdown("MarkdownFile")
Output:
| | A | B | |---:|----:|----:| | 0 | 5 | 25 | | 1 | 10 | 50 | | 2 | 15 | 60 | | 3 | 20 | 90 |
Example: Save Pandas DataFrame as a Markdown file without Index
# Import the pandas library as pd import pandas as pd # Create a DataFrame df = pd.DataFrame({'A': ['5', '10', '15', '20'], 'B': ['25', '50', '60', '90']}) # Display the Markdown table print(df.to_markdown(index=False)) # Save the DataFrame to a Markdown file without index df.to_markdown("MarkdownFile", index=False)
Output:
| A | B | |----:|----:| | 5 | 25 | | 10 | 50 | | 15 | 60 | | 20 | 90 |
Example: Markdown with Grid
# Import the pandas library as pd import pandas as pd # Create a DataFrame df = pd.DataFrame({'A': ['5', '10', '15', '20'], 'B': ['25', '50', '60', '90']}) # Display the Markdown table print(df.to_markdown(tablefmt="grid")) # Save the DataFrame to a Markdown file with grid df.to_markdown("MarkdownFile",tablefmt="grid")
Output:
+----+-----+-----+ | | A | B | +====+=====+=====+ | 0 | 5 | 25 | +----+-----+-----+ | 1 | 10 | 50 | +----+-----+-----+ | 2 | 15 | 60 | +----+-----+-----+ | 3 | 20 | 90 | +----+-----+-----+
If you want to learn Pandas, I recommend this book and free resource.