如何在Jupyter笔记本中将列表作为表输出?

2024-05-20 11:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我以前在某个地方见过一些例子,但就我的一生而言,我在网上搜索时找不到。

我有几行数据:

data = [[1,2,3],
        [4,5,6],
        [7,8,9],
        ]

我想把这些数据输出到一个表中,例如

+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
| 7 | 8 | 9 |
+---+---+---+

很明显,我可以使用像prettytable这样的库,或者下载pandas之类的东西,但我对此非常感兴趣。

我只想把我的行作为表格输出到我的Jupyter笔记本的单元格中。我该怎么做?


Tags: 数据pandasdata地方笔记本jupyter感兴趣例子
3条回答

我刚刚发现tabulate有一个HTML选项,使用起来相当简单。
与韦恩·沃纳的回答非常相似:

from IPython.display import HTML, display
import tabulate
table = [["Sun",696000,1989100000],
         ["Earth",6371,5973.6],
         ["Moon",1737,73.5],
         ["Mars",3390,641.85]]
display(HTML(tabulate.tabulate(table, tablefmt='html')))

仍在寻找一些简单的方法来创建更复杂的表格布局,比如使用latex语法和格式来合并单元格并在笔记本中进行变量替换:
Allow references to Python variables in Markdown cells #2958

我终于找到了我要找的jupyter/IPython documentation

我需要这个:

from IPython.display import HTML, display

data = [[1,2,3],
        [4,5,6],
        [7,8,9],
        ]

display(HTML(
   '<table><tr>{}</tr></table>'.format(
       '</tr><tr>'.join(
           '<td>{}</td>'.format('</td><td>'.join(str(_) for _ in row)) for row in data)
       )
))

(我可能稍微弄乱了理解,但display(HTML('some html here'))是我们需要的)

有一个很好的技巧:用pandas数据框包装数据。

import pandas as pd
data = [[1, 2], [3, 4]]
pd.DataFrame(data, columns=["Foo", "Bar"])

它显示的数据如下:

  | Foo | Bar |
0 | 1   | 2   |
1 | 3   | 4   |

相关问题 更多 >