Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh a Panda dataframe while printing using loop

How can i print a new dataframe and clear the last printed dataframe while using a loop? So it wont show all dataframes just the last one in the output?

Using print(df, end="\r") doesn't work

import pandas as pd
import numpy as np

while True:
    df = pd.DataFrame(np.random.rand(10,10))
    print(df)

If i get live data from an api to insert into the df, i'll use the while loop to constantly update the data. But how can i print only the newest dataframe instead of printing all the dataframes underneath each other in the output?

If i use the snippet below it does work, but i think there should be a more elegant solution.

import pandas as pd
import numpy as np

Height_DF = 10
Width_DF = 10

while True:
    
    df = pd.DataFrame(np.random.rand(10,10))
    print(df)

    for i in range(Height_DF + 1):
        sys.stdout.write("\033[F")
like image 556
Stijn van Leeuwen Avatar asked Mar 24 '26 17:03

Stijn van Leeuwen


1 Answers

This code allow to "clean" the Jupyter notebook cell, and allow to update/refresh the dataframe:

from IPython.display import display, clear_output

while True:
    df = pd.DataFrame(...)
    clear_output(wait=True)
    display(df)
like image 174
mountrix Avatar answered Mar 27 '26 07:03

mountrix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!