mercredi 20 mars 2019

while loop with if statements optimization

Following is the Dataframe I am starting from:

import pandas as pd
import numpy as np

d= {'PX_LAST':[1,2,3,3,3,1,2,1,1,1,3,3],'ma':[2,2,2,2,2,2,2,2,2,2,2,2],'action':[0,0,1,0,0,-1,0,1,0,0,-1,0]}
df_zinc = pd.DataFrame(data=d)

df_zinc

Now, I need to add a column called 'buy_sell', which: when 'action'==1, populates with 1 if 'PX_LAST' >'ma', and with -1 if 'PX_LAST'<'ma' when 'action'==-1, populates with the opposite of the previous non-zero value that was populated FYI: in my data, the row that needs to be filled with the opposite of the previous non-zero item is always at the same distance from the previous non-zero item (i.e., 2 in the current example). This should facilitate making the code.

the code that I made so far is the following. Though, it takes ages to execute. Any fixes proposed?

df_zinc['buy_sell'] = 0
index = 0

while index < df_zinc.shape[0]:
    if df_zinc['action'][index] == 1:
        if df_zinc['PX_LAST'][index]<df_zinc['ma'][index]:
            df_zinc.loc[index,'buy_sell'] = -1
            index=index+1
        elif df_zinc['PX_LAST'][index]>df_zinc['ma'][index]:
            df_zinc.loc[index,'buy_sell'] = 1
            index=index+1
    elif df_zinc['action'][index] == -1:
            df_zinc['PX_LAST'][index] = df_zinc['PX_LAST'][index-3]*-1 
            index=index+1

df_zinc

the resulting dataframe would look like this:

df_zinc['buy_sell'] = [0,0,1,0,0,-1,0,-1,0,0,1,0]

df_zinc

Aucun commentaire:

Enregistrer un commentaire