Pandas DataFrame to_markdown() Method


Preparation

Before any data manipulation can occur, four (4) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The Tabulate library enables formatted output.
  • The Tables library allows formatted output (table format).
  • The lxml library enables writing to an XML file.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install tabulate

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install tables

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install lxml

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import tabulate
import tables
import lxml

DataFrame.to_markdown()

The to_markdown() method provides a simple character-based border surrounding the cells/rows of a table when output to the terminal.

The syntax for this method is as follows:

DataFrame.to_markdown(buf=None, mode='wt', index=True, storage_options=None, **kwargs)
ParameterDescription
bufThis parameter is the buffer to write. If empty, a string returns.
modeThis depicts the mode the file opens in. The default is ‘wt‘.
indexIf True, add the index (row) labels to the output.
storage_optionsThis parameter contains extra options (dictionary format), such as host, port, username, etc.

Rivers Clothing had a 5-day sale on Winter Scarfs and Sweaters. The Sales Manager would like a Sales Report in this regard.

Run this code to view the formatted output.

df = pd.DataFrame({'2022-01-27': [33, 41],
                   '2022-01-28': [52, 43],
                   '2022-01-29': [48, 98],
                   '2022-01-30': [23, 23],
                   '2022-01-31': [49, 43]},
                   index=['Scarfs', 'Sweaters'])

df.loc['Total',:] = df.sum(axis=0)
print(df.to_markdown())
  • Line [1] creates a DataFrame from a dictionary of lists. The output saves to df.
  • Line [2] creates a Total row and calculates the daily sales. The output saves to df.
  • Line [3] outputs the formatted DataFrame to the terminal.

Output

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.