This is a Jupyter Notebook. You can write text, equations, and code in this notebook.
Using pandas.DataFrame.to_markdown()
# If necessary, install pandas and tabulate# You should have the pandas library installed if you installed Anaconda, # but if you do not, you can install both with the following terminal command:# conda install pandas tabulate# Import pandasimport pandas as pdfrom tabulate import tabulate# Create a sample DataFramedata = {"Name": ["Alice", "Bob", "Charlie"],"Age": [25, 30, 35],"City": ["New York", "London", "Paris"]}df = pd.DataFrame(data)# Print the DataFrame as Markdown, no index (row numbers)markdown_table = df.to_markdown(index=False)print(markdown_table)
| Name | Age | City |
|:--------|------:|:---------|
| Alice | 25 | New York |
| Bob | 30 | London |
| Charlie | 35 | Paris |
# You should also have the IPython package installed if you installed Anaconda# If not, you can install it with# conda install ipython# Import the Markdown display class. # This is what allows us to display Markdown in Jupyter Notebooks from IPython.display import display, Markdown# Display the Markdown tabledisplay(Markdown(markdown_table))
Name
Age
City
Alice
25
New York
Bob
30
London
Charlie
35
Paris
# Customising the Markdown table using the to_markdown() methodmarkdown_table = df.to_markdown( index=False, # Don't include index tablefmt="pipe", # Use pipe format floatfmt=".2f", # Format floats to 2 decimal places headers=["Name", "Age (Years)", "City"], # Custom headers colalign=("left", "center", "right") # Align columns)display(Markdown(markdown_table))
Name
Age (Years)
City
Alice
25
New York
Bob
30
London
Charlie
35
Paris
# Using the tabulate library to create a Markdown tableimport pandas as pdfrom IPython.display import display, Markdownfrom tabulate import tabulate# Create a sample DataFramedata = {"Product": ["Laptop", "Smartphone", "Tablet"],"Price": [999.99, 599.50, 299.75],"Stock": [50, 100, 75],"Rating": [4.5, 4.8, 4.2]}df = pd.DataFrame(data)# Create a formatted Markdown table# The floatfmt parameter formats columns as floats with 2 decimal places,# integers, and floats with 1 decimal place, respectivelymarkdown_table = tabulate( df, headers=["Product Name", "Price ($)", "Stock Quantity", "Customer Rating"], tablefmt="pipe", # Format as Markdown table floatfmt=(".2f", ".2f", "d", ".1f"), showindex=False, # Don't show the index (row numbers) numalign="right", # Align numbers to the right stralign="left"# Align strings (text, first column) to the left)# Display the table in the notebookdisplay(Markdown("### Product Inventory Summary"))display(Markdown(markdown_table))