मैं Jupyter नोटबुक में तालिका के रूप में सूचियों का उत्पादन कैसे करूं?


80

मुझे पता है कि मैंने पहले भी कुछ उदाहरण देखे हैं, लेकिन मेरे जीवन के लिए जब मैं चारों ओर गुगली कर रहा हूं तो मुझे यह नहीं मिल सकता है।

मेरे पास डेटा की कुछ पंक्तियाँ हैं:

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

और मैं इस डेटा को एक तालिका में आउटपुट करना चाहता हूं, जैसे

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

जाहिर है मैं एक पुस्तकालय का उपयोग कर सकता है जैसे कि सुंदर या पंडों या कुछ और डाउनलोड करें लेकिन मैं ऐसा करने में बहुत निराश हूं।

मैं सिर्फ अपनी जूपिटर नोटबुक सेल में टेबल के रूप में अपनी पंक्तियों को आउटपुट करना चाहता हूं। मैं यह कैसे करु?


क्या आप सिर्फ printफ़ंक्शन का उपयोग करना चाहते हैं ? क्या चौड़ाई में निर्धारित संख्याएँ (1 अंक, तीन अंक हैं?
tglaria

यहाँ मैंने पायथनिक अमूर्तता लिखी। बिना किसी परेशानी के कोड। :) jupyter_table_class.py
not_python

जवाबों:


85

मुझे अभी पता चला है कि सारणी में एक 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')))

फिर भी अधिक जटिल टेबल लेआउट बनाने के लिए उपयोग करने के लिए कुछ सरल की तलाश में जैसे लेटेक्स सिंटैक्स और कोशिकाओं को मर्ज करने के लिए स्वरूपण और नोटबुक में चर प्रतिस्थापन करना:
मार्केडाउन कोशिकाओं में पायथन चर के संदर्भ की अनुमति दें # 2958


संरेखित तार मेरे लिए काम नहीं किया! यह बाईं ओर स्ट्रिंग संरेखित नहीं करता है!
Mojtaba Khodadadi

@MojtabaKhodadadi ने इसे बारीकी से जांच नहीं की है, लेकिन ऐसा लगता है कि आप यहां संख्या बनाम srtings के लिए डिफ़ॉल्ट कॉलम तर्क सेट कर सकते हैं
22

आजकल भी बस tabulate.tabulate(table, tablefmt='html')काम करने लगता है (कोशिश की ज्यूपिटर 6.0.3, जुपिटरलैब 2.0.1)। अच्छा लगा!
zonksoft

82

एक अच्छी चाल है: पंडों के साथ डेटा को लपेटें DataFrame।

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

यह डेटा प्रदर्शित करता है जैसे:

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

14
जैसा कि कोई है जो पूरी तरह से डेटा विज्ञान के लिए सब कुछ के लिए अजगर से प्यार करता है, यह मुझे नौ-लाइन, चौगुनी-आयात, ट्रिपल फ़ंक्शन कॉल उत्तरों को देखकर बहुत दुखी करता है, जब बेस्ट लुकिंग उत्तर का शाब्दिक अर्थ है "एक पांडा वीडियो गेम।" मेरा अनुमान है: "यदि यह लंबा है - यह शायद गलत है!"
one_observation

1
तुम भी HTML का उपयोग कर के रूप में DataFrame दिखा सकते हैं to_html(), stackoverflow.com/a/29665452/2866660
wvengen

धन्यवाद! हां, स्वीकृत उत्तर को निश्चित रूप से इसे बदल दिया जाना चाहिए।
हेलन

59

मैंने आखिरकार ज्यूपिटर / आईपीथॉन प्रलेखन को फिर से पाया रहा हूं जिसकी मुझे तलाश थी।

मुझे इसकी आवश्यकता थी:

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'))हम क्या जरूरत है)


13

tabletext यह अच्छी तरह से फिट

import tabletext

data = [[1,2,30],
        [4,23125,6],
        [7,8,999],
        ]

print tabletext.to_text(data)

परिणाम:

┌───┬───────┬─────┐
│ 1230 │
├───┼───────┼─────┤
│ 4231256 │
├───┼───────┼─────┤
│ 78999 │
└───┴───────┴─────┘

4

यदि आप 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))

और फिर इसे इस तरह से उपयोग करें

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

यहाँ छवि विवरण दर्ज करें


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)

2

ठीक है, इसलिए यह मेरे मुकाबले थोड़ा कठिन था:

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

1

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

1

मुझे भी यहीं समस्या होती थी। मुझे ऐसा कुछ भी नहीं मिला जिससे मुझे मदद मिले इसलिए मैंने 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()

1

मैंने हाल ही में 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)

आउटपुट:

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

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)इसके डिफ़ॉल्ट तर्कों के साथ अधिकतम लचीलेपन के लिए प्रदान करने का इरादा है।

आप अनुकूलित कर सकते हैं

  • कॉलम पैड डिंग,
  • पंक्ति sep arator, (उदाहरण के लिए, pad='&', sep='\\\\\n'एक LaTeX तालिका के थोक के लिए)
  • एक सामान्य स्ट्रिंग प्रारूप में इनपुट को सामान्य करने के लिए इस्तेमाल किया जाने वाला फ़ंक्शन --- डिफ़ॉल्ट रूप से, अधिकतम सामान्यता के लिए यह है, 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
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.