2D Numpy 数组到 HTML 表?

Posted

技术标签:

【中文标题】2D Numpy 数组到 HTML 表?【英文标题】:2D Numpy array to HTML table? 【发布时间】:2013-11-06 11:51:24 【问题描述】:

这是我的 numpy 数组:

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]])

这是我的标题行:

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

这是我的第一篇专栏:

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

我想把它全部放在一个 html 表格中,如下所示:

<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>

有没有pythonic方法可以做到这一点?或者有什么我可以使用的模块(在 Python 3 上)?

谢谢。

【问题讨论】:

【参考方案1】:

pandas DataFrame 有一个to_html 方法:

import numpy as np
import pandas as pd

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,],])

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

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

df = pd.DataFrame(num, index=prices, columns=days)

html = df.to_html()

print(html)

输出:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>5 days</th>
      <th>10 days</th>
      <th>20 days</th>
      <th>60 days</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>AAPL</th>
      <td>0.178996</td>
      <td>0.330933</td>
      <td>0.207635</td>
      <td>0.061308</td>
    </tr>
    <tr>
      <th>ADBE</th>
      <td>0.203929</td>
      <td>0.426531</td>
      <td>0.333259</td>
      <td>0.104740</td>
    </tr>
    <tr>
      <th>AMD</th>
      <td>0.170382</td>
      <td>0.190820</td>
      <td>0.101197</td>
      <td>0.090324</td>
    </tr>
    <tr>
      <th>AMZN</th>
      <td>-0.106066</td>
      <td>-0.136805</td>
      <td>-0.131291</td>
      <td>-0.036843</td>
    </tr>
    <tr>
      <th>CRM</th>
      <td>0.203194</td>
      <td>0.283410</td>
      <td>0.209949</td>
      <td>0.117285</td>
    </tr>
    <tr>
      <th>EXPE</th>
      <td>0.043969</td>
      <td>0.237035</td>
      <td>0.093597</td>
      <td>0.114860</td>
    </tr>
    <tr>
      <th>FB</th>
      <td>0.278013</td>
      <td>-0.057693</td>
      <td>-0.062028</td>
      <td>0.047228</td>
    </tr>
  </tbody>
</table>

【讨论】:

【参考方案2】:

Jupyter 笔记本用户应该会发现这很有用。如果有人将其作为适当的模块实现,请在 cmets 中告诉我!

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)

我们使用 Numpy view 函数来启用这个接口:

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

诀窍在于这种类型很有效,只要您的一个数组设置了视图,结果将始终是 PrettyArray。例如,这仍然会打印第二行结果的 HTML 表格:

arr = np.random.normal(size=(4, 8)).view(PrettyArray)
np.eye(4) @ arr**2 @ np.eye(8)

【讨论】:

以上是关于2D Numpy 数组到 HTML 表?的主要内容,如果未能解决你的问题,请参考以下文章

numpy 3D 图像数组到 2D

如何将 1d numpy 数组附加到 2d numpy 数组 python

如何将 2D float numpy 数组转换为 2D int numpy 数组?

3d Numpy 数组到 2d

3d Numpy 数组到 2d

numpy with python:将3d数组转换为2d