【问题标题】:Can I display a Dataframe in Output form from within a while loop?我可以在 while 循环中以输出形式显示数据框吗?
【发布时间】:2020-03-04 07:49:36
【问题描述】:

我正在尝试编写一个小型 python 程序来管理 sql db 中的表。我的功能之一是查询数据库,并将其存储在数据框中,然后以输出格式显示数据框。这个函数本身运行良好,但是当它被放置在一个while循环中时,它不会显示输出,因为循环仍在运行。

在下面运行此命令将以通常的干净数据帧格式输出 df。

def show_table(x,k={}):
    mydb=connect(k.get("a_p"), k.get("h"), k.get("u"), k.get("p"), k.get("db"))
    try:
        quack = pd.read_sql('SELECT * FROM '+str(x), mydb)
    except mysql.connector.Error as e:
        print("An error occured: {}".format(e))
    finally:
        if (mydb.is_connected()):
            mydb.close()
    return quack
show_table(stock_main,sql)

当放在我的while循环中时,它不会输出。

i=True
while i != "":
    i = input("select table")
    if i in tables:
        show_table(i,sql)
    else:
        print(False)

如果我为 show_table 分配一个变量,然后打印它,它将打印出表格但不是以干净的数据帧输出格式,然后继续循环。

【问题讨论】:

    标签: python pandas dataframe while-loop


    【解决方案1】:

    就用这个吧:

    from IPython.display import display, HTML
    df = pd.DataFrame({'col1': [1,2,3], 'col2': [3,4,5]})
    i = 0
    while i!=2:
        i+=1
        display(HTML(df.to_html()))
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2018-12-29
      • 2023-04-03
      • 2020-07-22
      • 2011-02-24
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多