簡體   English   中英

如何正確循環熊貓數據框創建新列

[英]How to correctly loop pandas dataframe creating new columns

我有這個數據框(名稱: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      

我想根據列值創建新列“pl_stop”,所以我使用:

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

問題是當我打印 res_d 時它不顯示“pl_stop”列,我不明白問題出在哪里,有什么想法嗎?

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)

我最喜歡的方法是:

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

示例條件:

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

嘗試這個

填充 NaN 值:

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)

然后:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM