How do I output lists as a table in Jupyter notebook?

后端 未结 11 1023
灰色年华
灰色年华 2021-01-30 09:51

I know that I\'ve seen some example somewhere before but for the life of me I cannot find it when googling around.

I have some rows of data:

data = [[1,2         


        
相关标签:
11条回答
  • 2021-01-30 10:26

    If you don't mind using a bit of html, something like this should work.

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

    And then use it like this

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

    0 讨论(0)
  • 2021-01-30 10:30

    I recently used prettytable for rendering a nice ASCII table. It's similar to the postgres CLI output.

    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)
    

    Output:

    +-----+-----+-------+
    | one | two | three |
    +-----+-----+-------+
    |  1  |  2  |   3   |
    |  4  |  5  |   6   |
    |  7  |  8  |   9   |
    +-----+-----+-------+
    
    0 讨论(0)
  • 2021-01-30 10:32

    I want to output a table where each column has the smallest possible width, where columns are padded with white space (but this can be changed) and rows are separated by newlines (but this can be changed) and where each item is formatted using str (but...).


    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)
    

    The function signature, ftable(tbl, pad=' ', sep='\n', normalize=str), with its default arguments is intended to provide for maximum flexibility.

    You can customize

    • the column padding,
    • the row separator, (e.g., pad='&', sep='\\\\\n' to have the bulk of a LaTeX table)
    • the function to be used to normalize the input to a common string format --- by default, for the maximum generality it is str but if you know that all your data is floating point lambda item: "%.4f"%item could be a reasonable choice, etc.

    Superficial testing:

    I need some test data, possibly involving columns of different width so that the algorithm needs to be a little more sophisticated (but just a little bit;)

    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
    
    0 讨论(0)
  • 2021-01-30 10:33

    There is a nice trick: wrap the data with pandas DataFrame.

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

    It displays data like:

      | Foo | Bar |
    0 | 1   | 2   |
    1 | 3   | 4   |
    
    0 讨论(0)
  • 2021-01-30 10:33

    You could try to use the following function

    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)
    
    0 讨论(0)
  • 2021-01-30 10:39

    Ok, so this was a bit harder than I though:

    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
    

    This should work for variable number of rows, columns and number of digits (for numbers)

    data = [[1,2,30],
            [4,23125,6],
            [7,8,999],
            ]
    print print_matrix(data)
    >>>>+-------+-------+-------+
        |   1   |   2   |  30   |
        +-------+-------+-------+
        |   4   | 23125 |   6   |
        +-------+-------+-------+
        |   7   |   8   |  999  |
        +-------+-------+-------+
    
    0 讨论(0)
提交回复
热议问题