2

I want to define the state between two rows and two column in pandas

              Open Time   Close    shortEMA     longEMA   Buy  Sell
1 2020-12-23 11:49:00  598.76  598.651908  598.902220   NaN   NaN
2 2020-12-23 11:50:00  598.61  599.637938  598.875654   NaN   NaN  if (shortEMA > longEMA)
3 2020-12-23 11:51:00  598.13  597.468626  598.807868   NaN   NaN  and (shortEMA < longEMA) Buy = Close

I try some thing like this but must have some issue with to get condition from two row i thing:

data.loc[(data['shortEMA'][-1:] < data['longEMA'][-1:]) & (data['shortEMA'] > data['longEMA']), 'Buy'] = data['Close']
5
  • What's the desired output? Dec 23, 2020 at 12:34
  • put to column buy number from close column if condition
    – Roman
    Dec 23, 2020 at 12:35
  • I mean how the dataframe would look like. Dec 23, 2020 at 12:35
  • same like what i post just not have on right side if condition
    – Roman
    Dec 23, 2020 at 12:37
  • like this work data.loc[(data['shortEMA'] > data['longEMA']), 'Buy'] = data['Close'] work but i want add condition from before row
    – Roman
    Dec 23, 2020 at 12:38

1 Answer 1

1

You were close with your current code, but in order to reference the previous row you needed to shift it downwards first.

For a cleaner solution, we can build a simple boolean condition using shift and eval:

m = df.shift().eval('shortEMA > longEMA') & df.eval('shortEMA < longEMA')
df.loc[m, 'Buy'] = df['Close']

df
         Open      Time   Close    shortEMA     longEMA     Buy  Sell
1  2020-12-23  11:49:00  598.76  598.651908  598.902220     NaN   NaN
2  2020-12-23  11:50:00  598.61  599.637938  598.875654     NaN   NaN
3  2020-12-23  11:51:00  598.13  597.468626  598.807868  598.13   NaN

Or, as a one liner using np.where:

df['Buy'] = np.where(
    df.shift().eval('shortEMA > longEMA') & df.eval('shortEMA < longEMA'),
    df['Close'],
    np.nan)

df
         Open      Time   Close    shortEMA     longEMA     Buy  Sell
1  2020-12-23  11:49:00  598.76  598.651908  598.902220     NaN   NaN
2  2020-12-23  11:50:00  598.61  599.637938  598.875654     NaN   NaN
3  2020-12-23  11:51:00  598.13  597.468626  598.807868  598.13   NaN

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.