Python 如何在Jupyter笔记本中将列表输出为表格?
我知道我以前在某个地方见过一些例子,但就我的一生而言,我在谷歌搜索时找不到它 我有一些数据行:Python 如何在Jupyter笔记本中将列表输出为表格?,python,jupyter-notebook,Python,Jupyter Notebook,我知道我以前在某个地方见过一些例子,但就我的一生而言,我在谷歌搜索时找不到它 我有一些数据行: data = [[1,2,3], [4,5,6], [7,8,9], ] 我想把这些数据输出到一个表中,例如 +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 4 | 5 | 6 | +---+---+---+ | 7 | 8 | 9 | +---+---+---+ 显然,我可以使用像prettytable这样的
data = [[1,2,3],
[4,5,6],
[7,8,9],
]
我想把这些数据输出到一个表中,例如
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 4 | 5 | 6 |
+---+---+---+
| 7 | 8 | 9 |
+---+---+---+
显然,我可以使用像prettytable这样的库,或者下载熊猫之类的东西,但我对此非常感兴趣
我只想将我的行作为表格输出到我的Jupyter笔记本单元中。如何执行此操作?您可以尝试使用以下功能
def tableIt(data):
for lin in data:
print("+---"*len(lin)+"+")
for inlin in lin:
print("|",str(inlin),"", end="")
print("|")
print("+---"*len(lin)+"+")
data = [[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3],[1,2,3,2,3]]
tableIt(data)
好吧,这比我想象的要难一些:
def print_matrix(list_of_list):
number_width = len(str(max([max(i) for i in list_of_list])))
cols = max(map(len, list_of_list))
output = '+'+('-'*(number_width+2)+'+')*cols + '\n'
for row in list_of_list:
for column in row:
output += '|' + ' {:^{width}d} '.format(column, width = number_width)
output+='|\n+'+('-'*(number_width+2)+'+')*cols + '\n'
return output
这适用于可变的行数、列数和位数(对于数字)
我终于找到了我要找的那个
我需要这个:
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)
)
))
从IPython.display导入HTML,显示
数据=[[1,2,3],
[4,5,6],
[7,8,9],
]
显示(HTML)(
“{}”格式(
'',加入(
数据行的“{}”格式(“”.join(str(u)表示行中的“{}”))
)
))
(我可能稍微弄乱了理解,但是display(HTML('some HTML here'))
是我们需要的)很适合这个
import tabletext
data = [[1,2,30],
[4,23125,6],
[7,8,999],
]
print tabletext.to_text(data)
结果:
┌───┬───────┬─────┐
│ 1 │ 2 │ 30 │
├───┼───────┼─────┤
│ 4 │ 23125 │ 6 │
├───┼───────┼─────┤
│ 7 │ 8 │ 999 │
└───┴───────┴─────┘
我刚刚发现它有一个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语法和格式来合并单元格,并在笔记本中进行变量替换:一组通用函数,用于将任何python数据结构(嵌套在一起的目录和列表)呈现为HTML
从IPython.display导入HTML,显示
定义渲染列表html(l):
o=[]
对于l中的e:
o、 附加(“%s ”%\u呈现为\u html(e))
返回“%s”%”。加入(o)
def_render_dict_html(d):
o=[]
对于d.项()中的k,v:
o、 追加(“%s%s%”(str(k),\u呈现为\u html(v)))
返回“%s”%”。加入(o)
def_呈现为_html(e):
o=[]
如果存在(e,列表):
o、 附加(_render_list_html(e))
elif isinstance(e,dict):
o、 附加(_render_dict_html(e))
其他:
o、 附加(str(e))
返回“%s”%”。加入(o)
def呈现为html(e):
显示(HTML(_render_as_HTML(e)))
我以前也有同样的问题。我找不到任何对我有帮助的东西,所以我最终制作了类PrintTable
——下面的代码。还有一个输出。用法很简单:
ptobj = PrintTable(yourdata, column_captions, column_widths, text_aligns)
ptobj.print()
或者在一行中:
PrintTable(yourdata, column_captions, column_widths, text_aligns).print()
输出:
-------------------------------------------------------------------------------------------------------------
Name | Column 1 | Column 2 | Column 3 | Column 4 | Column 5
-------------------------------------------------------------------------------------------------------------
Very long name 0 | 0 | 0 | 0 | 0 | 0
Very long name 1 | 1 | 2 | 3 | 4 | 5
Very long name 2 | 2 | 4 | 6 | 8 | 10
Very long name 3 | 3 | 6 | 9 | 12 | 15
Very long name 4 | 4 | 8 | 12 | 16 | 20
Very long name 5 | 5 | 10 | 15 | 20 | 25
Very long name 6 | 6 | 12 | 18 | 24 | 30
Very long name 7 | 7 | 14 | 21 | 28 | 35
Very long name 8 | 8 | 16 | 24 | 32 | 40
Very long name 9 | 9 | 18 | 27 | 36 | 45
Very long name 10 | 10 | 20 | 30 | 40 | 50
Very long name 11 | 11 | 22 | 33 | 44 | 55
Very long name 12 | 12 | 24 | 36 | 48 | 60
Very long name 13 | 13 | 26 | 39 | 52 | 65
Very long name 14 | 14 | 28 | 42 | 56 | 70
Very long name 15 | 15 | 30 | 45 | 60 | 75
Very long name 16 | 16 | 32 | 48 | 64 | 80
Very long name 17 | 17 | 34 | 51 | 68 | 85
Very long name 18 | 18 | 36 | 54 | 72 | 90
Very long name 19 | 19 | 38 | 57 | 76 | 95
-------------------------------------------------------------------------------------------------------------
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
+-----+-----+-------+
类的代码PrintTable
# -*- coding: utf-8 -*-
# Class
class PrintTable:
def __init__(self, values, captions, widths, aligns):
if not all([len(values[0]) == len(x) for x in [captions, widths, aligns]]):
raise Exception()
self._tablewidth = sum(widths) + 3*(len(captions)-1) + 4
self._values = values
self._captions = captions
self._widths = widths
self._aligns = aligns
def print(self):
self._printTable()
def _printTable(self):
formattext_head = ""
formattext_cell = ""
for i,v in enumerate(self._widths):
formattext_head += "{" + str(i) + ":<" + str(v) + "} | "
formattext_cell += "{" + str(i) + ":" + self._aligns[i] + str(v) + "} | "
formattext_head = formattext_head[:-3]
formattext_head = " " + formattext_head.strip() + " "
formattext_cell = formattext_cell[:-3]
formattext_cell = " " + formattext_cell.strip() + " "
print("-"*self._tablewidth)
print(formattext_head.format(*self._captions))
print("-"*self._tablewidth)
for w in self._values:
print(formattext_cell.format(*w))
print("-"*self._tablewidth)
#-*-编码:utf-8-*-
#阶级
类打印表:
定义初始(自身、值、标题、宽度、对齐):
如果不是全部([len(值[0])==len(x)表示[caption,widths,aligns]]中的x):
引发异常()
self._tablewidth=总和(宽度)+3*(标题)-1)+4
自我价值=价值
自我。_字幕=字幕
自身宽度=宽度
自对齐=对齐
def打印(自):
self.\u printTable()
def_打印表(自):
formattext_head=“”
formattext_单元格=“”
对于枚举中的i,v(自身宽度):
formattext_head+=“{”+str(i)+:“,“>”,“>”,“>”,“>”])。print()
我想输出一个表,其中每列的宽度尽可能小,
其中列用空格填充(但可以更改),行用换行符分隔(但可以更改),并且每个项都使用str
(但…)进行格式化
函数签名,
ftable(tbl,pad='',sep='\n',normalize=str)
及其默认参数旨在
提供最大的灵活性
您可以自定义
- 列padding
- 行separator(例如,
以拥有LaTeX表的大部分)pad='&',sep='
- 用于将输入规范化为公共字符串的函数
格式---默认情况下,为了最大的通用性,它是
,但如果 您知道所有数据都是浮点str
可能是一个合理的选择,等等lambda项: “%.4f”%item
表面测试: 我需要一些测试数据,可能涉及不同宽度的列 因此,算法需要更复杂一点(但只是稍微复杂一点;)
有一个很好的技巧:用DataFrame包装数据
import pandas as pd
data = [[1, 2], [3, 4]]
pd.DataFrame(data, columns=["Foo", "Bar"])
它显示如下数据:
| Foo | Bar |
0 | 1 | 2 |
1 | 3 | 4 |
我最近使用了
prettytable
来呈现一个漂亮的ASCII表,它类似于postgres CLI输出
import pandas as pd
from prettytable import PrettyTable
data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(data, columns=['one', 'two', 'three'])
def generate_ascii_table(df):
x = PrettyTable()
x.field_names = df.columns.tolist()
for row in df.values:
x.add_row(row)
print(x)
return x
generate_ascii_table(df)
输出:
-------------------------------------------------------------------------------------------------------------
Name | Column 1 | Column 2 | Column 3 | Column 4 | Column 5
-------------------------------------------------------------------------------------------------------------
Very long name 0 | 0 | 0 | 0 | 0 | 0
Very long name 1 | 1 | 2 | 3 | 4 | 5
Very long name 2 | 2 | 4 | 6 | 8 | 10
Very long name 3 | 3 | 6 | 9 | 12 | 15
Very long name 4 | 4 | 8 | 12 | 16 | 20
Very long name 5 | 5 | 10 | 15 | 20 | 25
Very long name 6 | 6 | 12 | 18 | 24 | 30
Very long name 7 | 7 | 14 | 21 | 28 | 35
Very long name 8 | 8 | 16 | 24 | 32 | 40
Very long name 9 | 9 | 18 | 27 | 36 | 45
Very long name 10 | 10 | 20 | 30 | 40 | 50
Very long name 11 | 11 | 22 | 33 | 44 | 55
Very long name 12 | 12 | 24 | 36 | 48 | 60
Very long name 13 | 13 | 26 | 39 | 52 | 65
Very long name 14 | 14 | 28 | 42 | 56 | 70
Very long name 15 | 15 | 30 | 45 | 60 | 75
Very long name 16 | 16 | 32 | 48 | 64 | 80
Very long name 17 | 17 | 34 | 51 | 68 | 85
Very long name 18 | 18 | 36 | 54 | 72 | 90
Very long name 19 | 19 | 38 | 57 | 76 | 95
-------------------------------------------------------------------------------------------------------------
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
+-----+-----+-------+
如果您不介意使用一点html,类似的东西应该可以工作
from IPython.display import HTML, display
def display_table(data):
html = "<table>"
for row in data:
html += "<tr>"
for field in row:
html += "<td><h4>%s</h4><td>"%(field)
html += "</tr>"
html += "</table>"
display(HTML(html))
你想只使用
打印功能吗?数字的宽度是固定的吗(1位,3位?这里我写了pythonic abstraction.code,不费吹灰之力):对齐字符串对我来说不起作用!它不能将字符串向左对齐!@MojtabaKhodadadi没有仔细检查它,但看起来你可以为srtings vs number设置默认列参数。现在甚至只需tablate.tablate(table,tablefmt='html')
似乎就可以了(试过Jupyter 6.0.3,JupyterLab 2.0.1).很好!作为一个除了数据科学之外,对python的热爱之人,看到九行、四重导入、三重函数调用的答案被选中时,我真的很难过,因为最漂亮的答案是字面上的“熊猫数据帧”。我的启发是:“如果它很长——它可能是错的!”您甚至可以使用to_HTML()
将数据框显示为HTML,请参见,谢谢!是的,接受的答案肯定应该更改为此答案。
import pandas as pd
from prettytable import PrettyTable
data = [[1,2,3],[4,5,6],[7,8,9]]
df = pd.DataFrame(data, columns=['one', 'two', 'three'])
def generate_ascii_table(df):
x = PrettyTable()
x.field_names = df.columns.tolist()
for row in df.values:
x.add_row(row)
print(x)
return x
generate_ascii_table(df)
+-----+-----+-------+
| one | two | three |
+-----+-----+-------+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
+-----+-----+-------+
from IPython.display import HTML, display
def display_table(data):
html = "<table>"
for row in data:
html += "<tr>"
for field in row:
html += "<td><h4>%s</h4><td>"%(field)
html += "</tr>"
html += "</table>"
display(HTML(html))
data = [[1,2,3],[4,5,6],[7,8,9]]
display_table(data)