如何在显示更新后的DataFrame前清除已输出的旧DataFrame?
解决DataFrame刷新时清除旧输出的问题
针对你用display()展示DataFrame的场景,在Jupyter Notebook/Lab环境下可以用IPython提供的clear_output()函数来清除旧输出,具体操作如下:
首先导入
clear_output工具:from IPython.display import clear_output修改循环代码,在每次
display()之前调用clear_output(),推荐加上wait=True参数避免刷新时闪烁(会等新的DataFrame准备好后再清除旧内容):import time from IPython.display import clear_output while(True): refresh_prices() clear_output(wait=True) # 清除之前的输出 display(portfoliodf) time.sleep(60)
如果是在普通终端环境运行(而非Jupyter),可以用os模块的系统清屏命令:
- Windows系统:
os.system('cls') - Linux/macOS系统:
os.system('clear')
不过这种方式更适配打印语句,用display()的话还是Jupyter环境的方案更合适。
内容的提问来源于stack exchange,提问作者Isaac Chan
相关产品推荐
相关产品推荐

