Header

Print tables in format recognized by Zim-wiki

Author: Paulo van Breugel
Updated on: 26-07-17

Question

If you work with Pandas dataframes in Python, you can view the table by printing it to screen. For example:

# Import libraries
import numpy as np
import pandas as pd

# Create dataframe
df = pd.DataFrame({'one' : [1., 2., 3., 4.],
				   'two' : [4., 3., 2., 1.]})

# Print dataframe to screen
print(df)

This will print the table to screen as:

   one  two
0  1.0  4.0
1  2.0  3.0
2  3.0  2.0
3  4.0  1.0

but what if we want to show the table in a report or on a web page?

Answer

With the tabulate package we can export the table in various formats including html and Latex. If you want to use the table in a Latex document, for example, you can run:

# Load the tabulate library
from tabulate import tabulate

print tabulate(df, headers=df.columns, tablefmt="latex",
               showindex=False, floatfmt=".2f")

Will print the following to screen:

\begin{tabular}{rr}
\hline
   one &   two \\
\hline
  1.00 &  4.00 \\
  2.00 &  3.00 \\
  3.00 &  2.00 \\
  4.00 &  1.00 \\
\hline
\end{tabular}

If you use this in a Latex editor, you'll get:

I am writing this post in Zim-wiki, a graphical text editor that can be used to maintain a collection of wiki pages. In this case, I can export the same dataframe using the 'pipe' option. This is a format that Zim-wiki will automatically convert to a table. For example:

print tabulate(df, headers=df.columns, tablefmt="pipe",
			   showindex=False, floatfmt=".2f")

will print the following to screen:

|   one |   two |
|------:|------:|
|  1.00 |  4.00 |
|  2.00 |  3.00 |
|  3.00 |  2.00 |
|  4.00 |  1.00 |

When you copy-paste this in a Zim-notebook page, and reload the page, you will get (showing a screenshot of the table as it looks like in Zim):

Check out the manual page of Tabulate for all the supported table formats and the required syntax.

Tags

Software: @pandas @python @tabulate @zimwiki
Subject: @tables

If you have questions

If you have questions or comments about the text, let me know. You can use this contact form. Please make sure to include the page title ("Print tables in format recognized by Zim-wiki") or page name ("print-table-in-zimwiki-format").