2016-02-02 322 views
32

我知道我以前在某個地方見過一些例子,但對於我的生活,我無法在Google搜索時找到它。如何在Jupyter筆記本中將列表輸出爲表格?

我有數據的某些行:

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

我想輸出的表格,例如這個數據

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

很明顯,我可以使用像可愛的圖書館或下載熊貓或其他東西,但我很無心這樣做。

我只想在我的Jupyter筆記本電腦中輸出我的行作爲表格。我該怎麼做呢?

+0

你想只使用'print'的功能呢?數字的寬度是固定的(1位數,3位數? – tglaria

回答

27

我終於重新找到了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'))是我們所需要的)

2

你可以嘗試使用下面的函數

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

好了,所以這是一個有點難度比我還以爲:

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 

這應該行,列和數量的可變數量的工作的數字(數字)

data = [[1,2,30], 
     [4,23125,6], 
     [7,8,999], 
     ] 
print print_matrix(data) 
>>>>+-------+-------+-------+ 
    | 1 | 2 | 30 | 
    +-------+-------+-------+ 
    | 4 | 23125 | 6 | 
    +-------+-------+-------+ 
    | 7 | 8 | 999 | 
    +-------+-------+-------+ 
4

tabletext適應這口井

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 │ 
└───┴───────┴─────┘ 
28

我剛剛發現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'))) 

還在尋找一些簡單的使用,以創建更復雜的表格佈局像乳膠語法和格式合併單元格,並在筆記本上做變量代換:
Allow references to Python variables in Markdown cells #2958

1

用於將任何python數據結構(字符串和列表嵌套在一起)呈現爲HTML的通用函數集。

from IPython.display import HTML, display 

def _render_list_html(l): 
    o = [] 
    for e in l: 
     o.append('<li>%s</li>' % _render_as_html(e)) 
    return '<ol>%s</ol>' % ''.join(o) 

def _render_dict_html(d): 
    o = [] 
    for k, v in d.items(): 
     o.append('<tr><td>%s</td><td>%s</td></tr>' % (str(k), _render_as_html(v))) 
    return '<table>%s</table>' % ''.join(o) 

def _render_as_html(e): 
    o = [] 
    if isinstance(e, list): 
     o.append(_render_list_html(e)) 
    elif isinstance(e, dict): 
     o.append(_render_dict_html(e)) 
    else: 
     o.append(str(e)) 
    return '<html><body>%s</body></html>' % ''.join(o) 

def render_as_html(e): 
    display(HTML(_render_as_html(e))) 
0

我曾經有過同樣的問題。我找不到任何可以幫助我的東西,所以我最終編寫了類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 
------------------------------------------------------------------------------------------------------------- 

爲類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) 

示範

的代碼
# Demonstration 

headername = ["Column {}".format(x) for x in range(6)] 
headername[0] = "Name" 
data = [["Very long name {}".format(x), x, x*2, x*3, x*4, x*5] for x in range(20)] 

PrintTable(data, \ 
     headername, \ 
     [70, 10, 10, 10, 10, 10], \ 
     ["<",">",">",">",">",">"]).print() 
0

欲輸出,其中每列具有最小可能寬度, 其中列與白色空間填充(但這是可以改變的)和行由換行分隔的表(但是這可以更改)以及使用str(但是...)格式化每個項目的位置。


def ftable(tbl, pad=' ', sep='\n', normalize=str): 

    # normalize the content to the most useful data type 
    strtbl = [[normalize(it) for it in row] for row in tbl] 

    # next, for each column we compute the maximum width needed 
    w = [0 for _ in tbl[0]] 
    for row in strtbl: 
     for ncol, it in enumerate(row): 
      w[ncol] = max(w[ncol], len(it)) 

    # a string is built iterating on the rows and the items of `strtbl`: 
    # items are prepended white space to an uniform column width 
    # formatted items are `join`ed using `pad` (by default " ") 
    # eventually we join the rows using newlines and return 
    return sep.join(pad.join(' '*(wid-len(it))+it for wid, it in zip(w, row)) 
                 for row in strtbl) 

函數簽名,ftable(tbl, pad=' ', sep='\n', normalize=str),其默認參數旨在 提供最大的靈活性。

您可以自定義

  • 丁,
  • arator(例如,pad='&', sep='\\\\\n'有散裝乳膠表)
  • 該函數被用來正常化的輸入相同的字符串 格式---默認的最大共性是str,但如果 你知道,所有的數據是浮點lambda item: "%.4f"%item可能是一個合理的選擇,等

淺表性測試:

我需要一些測試數據,可能涉及不同的寬度 列,這樣的算法需要一點更復雜(但只是一點點;)

In [1]: from random import randrange 

In [2]: table = [[randrange(10**randrange(10)) for i in range(5)] for j in range(3)] 

In [3]: table 
Out[3]: 
[[974413992, 510, 0, 3114, 1], 
[863242961, 0, 94924, 782, 34], 
[1060993, 62, 26076, 75832, 833174]] 

In [4]: print(ftable(table)) 
974413992 510  0 3114  1 
863242961 0 94924 782  34 
    1060993 62 26076 75832 833174 

In [5]: print(ftable(table, pad='|')) 
974413992|510| 0| 3114|  1 
863242961| 0|94924| 782| 34 
    1060993| 62|26076|75832|833174