简体   繁体   中英

How to correctly loop pandas dataframe creating new columns

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?

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)

my fav method is:

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

example condition:

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

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

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