Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Numpy array to HTML table?

Here is my numpy array:

num = np.array([[ 0.17899619  0.33093259  0.2076353   0.06130814]
                [ 0.20392888  0.42653105  0.33325891  0.10473969]
                [ 0.17038247  0.19081956  0.10119709  0.09032416]
                [-0.10606583 -0.13680513 -0.13129103 -0.03684349]
                [ 0.20319428  0.28340985  0.20994867  0.11728491]
                [ 0.04396872  0.23703525  0.09359683  0.11486036]
                [ 0.27801304 -0.05769304 -0.06202813  0.04722761]])

Here is my header row:

days = ['5 days', '10 days', '20 days', '60 days']

And here is my first column:

prices = ['AAPL', 'ADBE', 'AMD', 'AMZN', 'CRM', 'EXPE', 'FB']

I want to put it all in one HTML table like this:

<table border=1>
    <tr>
        <th>Prices</th><th>5 days</th><th>10 days</th><th>20 days</th><th>60 days</th>
    </tr>
    <tr>
        <td>APPL</td><td>0.17899619</td><td>0.33093259</td><td>0.2076353</td><td>0.06130814</td>
    </tr>
    <tr>
        <td>ADBE</td><td>0.20392888</td><td>0.42653105</td><td>0.33325891</td><td>0.10473969</td>
    </tr>
    <tr>
        <td>AMD</td><td>0.17038247</td><td>0.19081956</td><td>0.10119709</td><td>0.09032416</td>
    </tr>
    <tr>
        <td>AMZN</td><td>-0.10606583</td><td>-0.13680513</td><td>-0.13129103</td><td>-0.03684349</td>
    </tr>
    <tr>
        <td>CRM</td><td>0.20319428</td><td>0.28340985</td><td>0.20994867</td><td>0.11728491</td>
    </tr>
    <tr>
        <td>EXPE</td><td>0.04396872</td><td>0.23703525</td><td>0.09359683</td><td>0.11486036</td>
    </tr>
    <tr>
        <td>FB</td><td>0.27801304</td><td>-0.05769304</td><td>-0.06202813</td><td>0.04722761</td>
    </tr>
</table>

Is there any pythonic way to do this? Or is there any module that i can use (on Python 3)?

Thanks.

like image 215
Michael Avatar asked Oct 27 '13 19:10

Michael


1 Answers

Jupyter notebook users should find this useful. Let me know in comments if anyone ever implements this as a proper module!

import numpy as np
from html import escape

class PrettyArray(np.ndarray):
    def _repr_html_(self):
        """Numpy array HTML representation function."""
        # Fallbacks for cases where we cannot format HTML tables
        if self.size > 10_000:
            return f"Large numpy array {self.shape} of {self.dtype}"
        if self.ndim != 2:
            return f"<pre>{escape(str(self))}</pre>"
        # Table format
        html = [f"<table><tr><th>{self.dtype}"]
        rows, columns = self.shape
        html += (f"<th>{j}" for j in range(columns))
        for i in range(rows):
            html.append(f"<tr><th>{i}")
            for j in range(columns):
                val = self[i, j]
                html.append("<td>")
                html.append(escape(f"{val:.2f}" if self.dtype == float else f"{val}"))
        html.append("</table>")
        return "".join(html)

We use the Numpy view function to enable this interface:

np.array([[1, 2], [3, 4]]).view(PrettyArray)

The trick is that this type sticks, and as long as one of your arrays has had the view set, the result will always be PrettyArray. For instance, this still prints a HTML table of the second row's result:

arr = np.random.normal(size=(4, 8)).view(PrettyArray)
np.eye(4) @ arr**2 @ np.eye(8)
like image 118
Tronic Avatar answered Oct 22 '22 08:10

Tronic