I'm looking for a logic to use a function with different operators.
Is there a way to implement the logic to use a boolean to determine the operator in the comparison? something along the lines of
while df["column"][i period] (> if bool_var else <=) min(df["column"])
Edit: can anyone explicitly show me how that logic would be implemented with the operator module?
while operator.gt(a, b) if bool_var else operator.eq(a, b): ?
CodePudding user response:
To avoid duplicated blocks in your if/else
branching all you need is to change your while
statement basing on positive
flag and comparison operator created by operator module:
from operator import eq, gt
def check_trends(df, set_lenght, positive=True, get_index=False):
periods = []
op = gt if positive else eq # select operator
for i in range(len(df.index)):
period = 0
while op(df["perc_btc"][i period], min(df["perc_btc"])):
if len(df.index) <= (i period 1):
break
period = 1
if period > set_lenght:
periods.append([i, period])
if get_index:
return [i, i period] # returns the last starting point
return periods
CodePudding user response:
Another way would be to make two separate comparisons, each contingent on newbool
. In this example a
is df["column"][i period]
and b
is min(df["column"]
.
>>> newbool = True
>>> a = 4
>>> b = 5
>>> (a>b and newbool) or (a<=b and not newbool)
False
>>> newbool = False
>>> (a>b and newbool) or (a<=b and not newbool)
True
>>> a = 6
>>> (a>b and newbool) or (a<=b and not newbool)
False
>>> newbool = True
>>> (a>b and newbool) or (a<=b and not newbool)
True
>>>
df["column"][i period]
Can probably be written as
df.loc[i period,"column"]
If it can it should be. Different choices for indexing.
To prevent a very long while statement the terms could be assigned to names before and at the bottom of the loop.
a = df.loc[i period,"column"]>min(df["column"]
b = min(df["column"]
while (a>b and newbool) or (a<=b and not newbool)):
# all the other stuff
...
a = df.loc[i period,"column"]
b = min(df["column"])