1. Sergey Astanin
  2. python-tabulate

Commits

Sergey Astanin  committed 4a77322 Merge

Merged in emsrc/python-tabulate-latex (pull request #2)

Support for NumPy record array input and LaTeX tabular output format.

  • Participants
  • Parent commits e23ad2c, f17eed8
  • Branches master

Comments (0)

Files changed (3)

File tabulate.py

View file
                               usecolons=False,
                               usehtmlattrs=True,
                               with_header_hide=[],
-                              without_header_hide=["linebelowheader"])}
+                              without_header_hide=["linebelowheader"]),
+                  "latex":
+                  TableFormat(lineabove=Line("\\begin{tabular}{r", "", "r", "}\n\hline"),
+                              linebelowheader=Line("\\hline", "", "", ""),
+                              linebetweenrows=None,
+                              linebelow=Line("\\hline\n\\end{tabular}", "", "", ""),
+                              headerrow=DataRow("", "&", "\\\\"),
+                              datarow=DataRow("", "&", "\\\\"),
+                              padding=1,
+                              usecolons=False,
+                              usehtmlattrs=False,
+                              with_header_hide=[],
+                              without_header_hide=[])}
 
 
 _invisible_codes = re.compile("\x1b\[\d*m")  # ANSI color codes
 
         if headers == "keys":
             headers = list(map(_text_type,keys))  # headers should be strings
-
     else:  # it's a usual an iterable of iterables, or a NumPy array
         rows = list(tabular_data)
-
-        if headers == "keys" and len(rows) > 0:  # keys are column indices
+        
+        if (headers == "keys" and 
+            hasattr(tabular_data, "dtype") and 
+            getattr(tabular_data.dtype, "names")):
+            # numpy record array
+            headers = tabular_data.dtype.names        
+        elif headers == "keys" and len(rows) > 0:  # keys are column indices
             headers = list(map(_text_type, range(len(rows[0]))))
 
     # take headers from the first row if necessary

File test_input.py

View file
         pass   # this test is optional
 
 
+def test_numpy_record_array():
+    "Printing a two-dimensional NumPy record array without header"
+    try:
+        import numpy
+        na = numpy.asarray([("Alice", 23, 169.5), 
+                            ("Bob", 27, 175.0)], 
+                           dtype={"names":["name","age","height"], 
+                                  "formats":["a32","uint8","f32"]})
+        expected = "\n".join([ "-----  --  -----",
+                               "Alice  23  169.5",
+                               "Bob    27  175",
+                               "-----  --  -----" ])
+        result   = tabulate(na)
+        print("Expected:\n%s\n" % expected)
+        print("Got:\n%s\n" % result)
+        assert expected == result
+    except ImportError:
+        print("test_numpy_2d_keys is skipped")
+        pass   # this test is optional
+    
+    
+def test_numpy_record_array_keys():
+    "Printing a two-dimensional NumPy record array with headers from fields"
+    try:
+        import numpy
+        na = numpy.asarray([("Alice", 23, 169.5), 
+                            ("Bob", 27, 175.0)], 
+                           dtype={"names":["name","age","height"], 
+                                  "formats":["a32","uint8","f32"]})
+        expected = "\n".join([ "name      age    height",
+                               "------  -----  --------",
+                               "Alice      23     169.5",
+                               "Bob        27     175"  ])
+        result   = tabulate(na, headers="keys")
+        print("Expected:\n%s\n" % expected)
+        print("Got:\n%s\n" % result)
+        assert expected == result
+    except ImportError:
+        print("test_numpy_2d_keys is skipped")
+        pass   # this test is optional
+    
+def test_numpy_record_array_headers():
+    "Printing a two-dimensional NumPy record array with user-supplied headers"
+    try:
+        import numpy
+        na = numpy.asarray([("Alice", 23, 169.5), 
+                            ("Bob", 27, 175.0)], 
+                           dtype={"names":["name","age","height"], 
+                                  "formats":["a32","uint8","f32"]})
+        expected = "\n".join([ "person      years     cm",
+                               "--------  -------  -----",
+                               "Alice          23  169.5",
+                               "Bob            27  175" ])
+        result   = tabulate(na, headers=["person", "years", "cm"])
+        print("Expected:\n%s\n" % expected)
+        print("Got:\n%s\n" % result)
+        assert expected == result
+    except ImportError:
+        print("test_numpy_2d_keys is skipped")
+        pass   # this test is optional
+    
+
 def test_pandas():
     "Printing a Pandas DataFrame."
     try:

File test_output.py

View file
+# -*- coding: utf-8 -*-
+
+"""Test output of the various forms of tabular data."""
+
+from __future__ import print_function
+from __future__ import unicode_literals
+from tabulate import tabulate
+
+
+def test_latex():
+    "Testing Latex output"
+    ll = [["a","one",1],["b","two",None]]
+    expected = u'0    1      2\n---  ---  ---\na    one    1\nb    two'
+    result   = tabulate(ll, headers="keys", tablefmt="latex")
+    expected = "\n".join([
+        r"\begin{tabular}{rrr}",
+        r"\hline",
+        r" 0   & 1   &   2 \\",
+        r"\hline",
+        r" a   & one &   1 \\",
+        r" b   & two &     \\",
+        r"\hline",
+        r"\end{tabular}"])
+    print("Expected:\n%s\n" % expected)
+    print("Got:\n%s\n" % result)
+    assert expected == result
+    
+