Given a numpy ndarray of strings, concatenate them into a html table. Args: contents: A np.ndarray of strings. May be 1d or 2d. In the 1d case, the table is laid out vertically (i.e. row-major). headers: A np.ndarray or list of string header names for the table. Returns
(contents, headers=None)
| 67 | |
| 68 | |
| 69 | def make_table(contents, headers=None): |
| 70 | """Given a numpy ndarray of strings, concatenate them into a html table. |
| 71 | |
| 72 | Args: |
| 73 | contents: A np.ndarray of strings. May be 1d or 2d. In the 1d case, the |
| 74 | table is laid out vertically (i.e. row-major). |
| 75 | headers: A np.ndarray or list of string header names for the table. |
| 76 | |
| 77 | Returns: |
| 78 | A string containing all of the content strings, organized into a table. |
| 79 | |
| 80 | Raises: |
| 81 | ValueError: If contents is not a np.ndarray. |
| 82 | ValueError: If contents is not 1d or 2d. |
| 83 | ValueError: If contents is empty. |
| 84 | ValueError: If headers is present and not a list, tuple, or ndarray. |
| 85 | ValueError: If headers is not 1d. |
| 86 | ValueError: If number of elements in headers does not correspond to number |
| 87 | of columns in contents. |
| 88 | """ |
| 89 | if not isinstance(contents, np.ndarray): |
| 90 | raise ValueError("make_table contents must be a numpy ndarray") |
| 91 | |
| 92 | if contents.ndim not in [1, 2]: |
| 93 | raise ValueError( |
| 94 | "make_table requires a 1d or 2d numpy array, was %dd" |
| 95 | % contents.ndim |
| 96 | ) |
| 97 | |
| 98 | if headers: |
| 99 | if isinstance(headers, (list, tuple)): |
| 100 | headers = np.array(headers) |
| 101 | if not isinstance(headers, np.ndarray): |
| 102 | raise ValueError( |
| 103 | "Could not convert headers %s into np.ndarray" % headers |
| 104 | ) |
| 105 | if headers.ndim != 1: |
| 106 | raise ValueError("Headers must be 1d, is %dd" % headers.ndim) |
| 107 | expected_n_columns = contents.shape[1] if contents.ndim == 2 else 1 |
| 108 | if headers.shape[0] != expected_n_columns: |
| 109 | raise ValueError( |
| 110 | "Number of headers %d must match number of columns %d" |
| 111 | % (headers.shape[0], expected_n_columns) |
| 112 | ) |
| 113 | header = "<thead>\n%s</thead>\n" % make_table_row(headers, tag="th") |
| 114 | else: |
| 115 | header = "" |
| 116 | |
| 117 | n_rows = contents.shape[0] |
| 118 | if contents.ndim == 1: |
| 119 | # If it's a vector, we need to wrap each element in a new list, otherwise |
| 120 | # we would turn the string itself into a row (see test code) |
| 121 | rows = (make_table_row([contents[i]]) for i in range(n_rows)) |
| 122 | else: |
| 123 | rows = (make_table_row(contents[i, :]) for i in range(n_rows)) |
| 124 | |
| 125 | return "<table>\n%s<tbody>\n%s</tbody>\n</table>" % (header, "".join(rows)) |
| 126 |
no test coverage detected
searching dependent graphs…