在新窗口中动态更新 Pandas 数据框

时间:2021-02-18 18:55:21

标签: python html pandas loops while-loop

我有随时间更新的数据,我想将其放入 Pandas 数据框中并在新窗口中打开。

例如,我有以下代码。这段代码我使用随机数生成器来模拟实时数据。

import time
import random
import pandas as pd
from IPython.display import HTML

def update():
    while True:
        data = {'Contract': ['D12-B South (Neptune)', 'G14 A&B (EBN)', 'K12-G (K12)'],
         'Flow[KWhr/Hr]': [round(36000*random.uniform(0.9,1.1)), round(85000*random.uniform(0.9,1.1)), round(2200*random.uniform(0.9,1.1))],
         'Nomination[KWHr/Hr]': [36000, 85000, 2200],      
         'SAB[KWHr]': [-10000, 2000, 5000]}
        df = pd.DataFrame(data, columns=['Contract', 'Nomination[KWHr/Hr]', 'Flow[KWhr/Hr]', 'SAB[KWHr]'])

        css = """<style>
        table { border-collapse: collapse; border: 3px solid #eee; }
        table tr th:first-child { background-color: #eeeeee; color: #333; font-weight: bold }
        table thead th { background-color: #eee; color: #000; }
        tr, th, td { border: 1px solid #ccc; border-width: 1px 0 0 1px; border-collapse: collapse;
        padding: 3px; font-family: monospace; font-size: 10px }</style>
        """
        s  = '<script type="text/Javascript">'
        s += 'var win = window.open("", "Title", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=780, height=200, top="+(screen.height-400)+", left="+(screen.width-840));'
        s += 'win.document.body.innerHTML = \'' + (df.to_html() + css).replace("\n",'\\') + '\';'
        s += '</script>'
        return (HTML(s+css))
        #print(HTML(s+css))
        #print(df)
        time.sleep(1)

update()

这只会用 return (HTML(s+css)) 循环一次,但我希望它不断循环。

如果我打印 HTML(s+css)df,它会不断循环但不会打开新窗口并填充数据框。

看来 return 使代码退出循环。我也试过 while False 在 true 语句之后,但这也不起作用。

有没有办法让我打开一个新窗口并每隔 n 秒更新一次新数据框?

0 个答案:

没有答案