Use columns 1 and 2 to populate column 3

  • A+

I’m a Python newbie and have the following pandas dataframe - I’m trying to write code that populates the ‘signal’ column as it is below:

Days    long_entry_flag long_exit_flag  signal  1      FALSE           TRUE      2      FALSE           FALSE     3      TRUE            FALSE            1  4      TRUE            FALSE            1  5      FALSE           FALSE            1  6      TRUE            FALSE            1  7      TRUE            FALSE            1  8      FALSE           TRUE      9      FALSE           TRUE      10     TRUE            FALSE            1  11     TRUE            FALSE            1  12     TRUE            FALSE            1  13     FALSE           FALSE            1  14     FALSE           TRUE      15     FALSE           FALSE     16     FALSE           TRUE      17     TRUE            FALSE            1  18     TRUE            FALSE            1  19     FALSE           FALSE            1  20     FALSE           FALSE            1  21     FALSE           TRUE     

My pseudo-code version would take the following steps

  1. Look down the [‘long_entry_flag’] column until entry condition is True (day 3 initially)
  2. Then we enter ‘1’ into [‘signal’] column every day until exit condition is True [‘long_exit_flag’]==True on day 8
  3. Then we look back to [‘long_entry_flag’] column to wait for the next entry condition (occurs on day 10)
  4. And again we enter ‘1’ into [‘signal’] column every day until exit condition is True (day 14)
  5. etc

Welcome ideas about ways to populate the ‘signal’ column rapidly if possible (using vectorisation?) - this is a subset of a large dataframe with tens of thousands of rows, and it is one of many dataframes being analysed in sequence.

Many thanks in advance!


You can do

# Assuming we're starting from the "outside" inside = False for ix, row in df.iterrows():     inside = not row['long_exit_flag'] if inside else row['long_entry_flag'][ix, 'signal'] = 1 if inside else np.nan 

which is going to give you exactly the output you posted.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: