简体   繁体   中英

slow for i loop in python

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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM