0

I have the column: dataset["RSI_14D"]

I want to assign:

1 if serie's rows <= 20

-1 if serie's rows >= 80

0 if serie's rows 20<x<80

I tried:

dataset.loc[dataset["RSI_14D"] >= 80, 'RSI_14D1'] = -1
dataset.loc[dataset["RSI_14D"] <= 20, 'RSI_14D1'] = 1
dataset.loc[dataset["RSI_14D1"] != 1 & -1, 'RSI_14D1'] = 0

but doesn't work

When I write:

dataset["RSI_14D1"][dataset["RSI_14D1"]  == -1  ]

it gives me 0 values even if there are 30+ rows with values >= 80

when I write

dataset["RSI_14D1"][dataset["RSI_14D1"]  == 1  ]

it is ok, it replaced the values

Trees Jin
  • 13
  • 3
  • you may be breaking your logic by setting all the 80+ to be -1 _before_ clearing the <=20 – ti7 Aug 05 '21 at 08:05
  • what does happen? how do you know it doesn't work? – ti7 Aug 05 '21 at 08:06
  • Because when I type: dataset["RSI_14D1"][dataset["RSI_14D1"] == -1 ] it gives me 0 values with "-1" even if there are 30+ values with values >= 80 – Trees Jin Aug 05 '21 at 08:09
  • Does this answer your question? [Pandas conditional creation of a series/dataframe column](https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column) – Henry Yik Aug 05 '21 at 08:15

1 Answers1

0

Your code doesn't work because for the last line of codes, the values of new column RSI_14D1 are still not defined for rows of RSI_14D with values between 20 and 80.

You can replace the last line of code to:

dataset.loc[dataset["RSI_14D"].between(20, 80,  inclusive='neither'), 'RSI_14D1'] = 0

or

dataset.loc[(dataset["RSI_14D"] > 20) & (dataset["RSI_14D"] < 80), 'RSI_14D1'] = 0

Alternative Solution

Alternatively, if you want to handle the case differently for when RSI_14D values are between 20 and 80, you can do it by setting default value of 0 for new column RSI_14D1, as follows:

# Add this line at the front:
dataset['RSI_14D1'] = 0

# Keep your first 2 lines of codes:
dataset.loc[dataset["RSI_14D"] >= 80, 'RSI_14D1'] = -1
dataset.loc[dataset["RSI_14D"] <= 20, 'RSI_14D1'] = 1
SeaBean
  • 22,547
  • 3
  • 13
  • 25
  • @TreesJin Added alternative solution. You can take a look. – SeaBean Aug 05 '21 at 08:50
  • @TreesJin Pleased to help! Remember that for programming, it is often easier to initialize a value for the most common scenario and add special handling for special cases. – SeaBean Aug 05 '21 at 11:18