Home > Mobile >  How to correctly loop pandas dataframe creating new columns
How to correctly loop pandas dataframe creating new columns

Time:07-10

I have this dataframe (name: res_d)

   time        entry  take_profit   stop_loss   
                
  2022-04-05    3881.5   False       3854.5     
  2022-04-06    3835.5   False       3816.5     
  2022-04-07    3767.0   3785.5      False      
  2022-04-08    3781.5   3793.5      False     
  2022-04-09    False    False       False      

I want to create new column "pl_stop" based on column values, so i use:

res_d = result_111.fillna(False)
for index, row in res_d.iterrows():

    if res_d['entry'].all() != False and res_d['take_profit'].all() == False and res_d['stop_loss'].all() != False:
    
           res_d['pl_stop'] = res_d['stop_loss'] - res_d['entry'] 

The problem is that when I print res_d it does not display the "pl_stop" column, I don't understand where is the problem, any ideas?

CodePudding user response:

my fav method is:

df.loc[(condition), 'new_column'] = 'value'

example condition:

(df.col >= 10) & (df.col2.notna())

CodePudding user response:

np.where((res_d['entry']!=False) & (res_d['take_profit']==False) & (res_d['stop_loss']!=False), res_d['stop_loss'] - res_d['entry'], np.nan)

CodePudding user response:

Try this

fill the NaN values:

res_d = res_d.fillna(False)

exp = (res_d['entry'].all() != False) and (res_d['take_profit'].all() == False) and (res_d['stop_loss'].all() != False)

then:

for index, row in res_d.iterrows():
    if exp:
        res_d['pl_stop'] = res_d['stop_loss'] - res_d['entry']
  • Related