0

I have a Pandas DataFrame.

df = pd.read_excel("data.xlsx")
df

B Price        S Price       Amount         %Change
500            600           100            4
80             300           220            4.2
485            800           315            3.65
59             300           241            4.56
487            1000          513            2.52
187            400           213            2
168            500           332            1.50
185            300           115            1.30
200            134           66             -5.56
100            16            84             -4.44
200            92            108            -4.15
100            44            56             -3
200            145           55             -2.98
102            36            62             -2.50
200            103           97             -2
301            207           94             -2.42

I want to apply this condition, if df["%Change"] column is greater or equal to 3 then set Result column value as Buy, if df["%Change"] column is smaller than or equal to -3 then set Result column value as Sell, and rest of the condition set Result column value as Wait on this dataframe.

if df["%Change"] >= 3:
      df["Result"] = "Buy"
      
elif df["%Change"] <= -3:
      df["Result"] = "Sell"
      
else:
      df["Result"] = "Wait"

Can you please tell me how can I do it programmatically.

Expected output:

B Price        S Price       Amount         %Change       Result
500            600           100            4             Buy
80             300           220            4.2           Buy
485            800           315            3.65          Buy
59             300           241            4.56          Buy
487            1000          513            2.52          Wait
187            400           213            2             Wait
168            500           332            1.50          Wait
185            300           115            1.30          Wait
200            134           66             -5.56         Sell
100            16            84             -4.44         Sell
200            92            108            -4.15         Sell
100            44            56             -3            Sell
200            145           55             -2.98         Wait
102            36            62             -2.50         Wait
200            103           97             -2            Wait
301            207           94             -2.42         Wait
ammely
  • 85
  • 1
  • 8

1 Answers1

0

use:

import numpy as np

conditions = [(df['%Change'] >= 3), (df['%Change'] <= -3)]
values = ['Buy', 'Sell']
df['result'] = np.select(conditions, values, 'wait')

Since you have strings in '%Change' column, you can use the following:

import numpy as np

conditions = [(df['%Change'].astype(float) >= 3), (df['%Change'].astype(float) <= -3)]
df['result'] = np.select(conditions, ['Buy', 'Sell'], 'wait')
print(df)
Amin Gheibi
  • 639
  • 1
  • 8
  • 15