Home > Back-end >  slow for i loop in python
slow for i loop in python

Time:11-20

I am having trouble optimizing a for i loop that uses time sequence data that bases the next result on the previous one.

import pandas as pd
import numpy as np
df= pd.Series(range(1,1000000))
df=df.to_frame(name="CusUnits")
df['UpperBoundary'] = 10
df['LowerBoundary'] = -10
from progress.bar import Bar
import time
from tqdm import tqdm
from time import sleep
length=len(df)
df.loc[0, 'Hedged'] = df.loc[0, 'CusUnits']

for i in tqdm(range(1, length)):
    if (df.loc[i, 'UpperBoundary'] > (df.loc[i-1, 'Hedged'] - df.loc[i, 'CusUnits']) > df.loc[i, 'LowerBoundary']):  df.loc[i, 'Hedged'] = df.loc[i-1, 'Hedged']     
    else :df.loc[i, 'Hedged'] =df.loc[i-1, 'CusUnits']

CodePudding user response:


for i in tqdm(range(1, length)):
    if (df.at[i, 'UpperBoundary'] > (df.at[i-1, 'Hedged'] - df.at[i, 'CusUnits']) > df.at[i, 'LowerBoundary']):  df.at[i, 'Hedged'] = df.at[i-1, 'Hedged']     
    else :df.at[i, 'Hedged'] =df.at[i-1, 'CusUnits']

the replacement of loc with at solved many thanks for you comments
  • Related