Skip a few line of code in rerun of python script

55 views Asked by At

df gets data from web.

df_new = df.drop(df.columns[[1, 2]],axis = 1)

once df_new is created the script wants to update / manipulate it by incrementally adding new columns during every rerun of say 1 minute

but as df_new is derived from df it gets recreated during each rerun thus going back to square one.

how to skip the second line, here, of the code during reruns. Run it only for the first time. The df is to be updated every 1 minute for rest of the script to run calculations and to also add new columns to existing df_new.

2

There are 2 answers

0
newby73 On

First of all, you should include your source code so we have context... Otherwise it's difficult to understand what is going on.

One possible solution is to use a variable to signify the state of the run. i.e.:

new = True

if new == True: 
    new = False
    df_new = df.drop(df.columns[[1, 2]],axis = 1)

Note: it seems as if you are creating a new "df_new" object each rerun. This is your problem: you need to create the "df_new" object exactly one time, and then each rerun, you create another "df" object off of the last "df" object you utilized.

0
nischal sharma On

You can use the if statement to check if the df_new DataFrame has already been created. If it has been created, you can skip the second line of code that creates the DataFrame and only update it using the new data.

# Create the DataFrame for the first time
if 'df_new' not in locals():
    df_new = df.drop(df.columns[[1, 2]], axis=1)

while True:
    # Update the DataFrame every minute
   

I hope this helps!