Search code examples
pythonpandasdataframebooleanseries

"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."


am extremely new and learning as I go. However cannot seem to fix this error - been on it for a while. This is the input:

# Signals

VWAPsignal = [0]*len(df)
backcandles = 4

for row in range(backcandles, len(df)):
    upt = 1
    dnt = 1
    for i in range(row-backcandles, row+1):
        if df.High[i]>=df.VWAP[i]:
            dnt=0
        if df.Low[i]<=df.VWAP[i]:
            upt=0
    if upt==1 and dnt==1:
        VWAPsignal[row]=3
    elif upt==1:
        VWAPsignal[row]=2
    elif dnt==1:
        VWAPsignal[row]=1

df['VWAPSignal'] = VWAPsignal

def TotalVWAPSignal(l):
    myclosedistance = df['7Period-Range']
    if (df.VWAPSignal[l] == 2)
        and (min (abs(df.VWAP[l]-df.High[l]), abs(df.VWAP[l]-df.Low[l])) <= myclosedistance):
            return 2
    if (df.VWAPSignal[l] == 1) 
        and (min (abs(df.VWAP[l]-df.High[l]), abs(df.VWAP[l]-df.Low[l]))<=myclosedistance):
            return 1  

TotSignal = [0]*len(df)
for row in range(0, len(df)):
    TotSignal[row] = TotalVWAPSignal(row)
df['TotalSignal'] = TotSignal

It returns the below error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-90a00c92cea7> in <module>
     30 TotSignal = [0]*len(df)
     31 for row in range(0, len(df)):
---> 32     TotSignal[row] = TotalVWAPSignal(row)
     33 df['TotalSignal'] = TotSignal

<ipython-input-27-90a00c92cea7> in TotalVWAPSignal(l)
     23 def TotalVWAPSignal(l):
     24     myclosedistance = df['7Period-Range']
---> 25     if (df.VWAPSignal[l] == 2) and (min (abs(df.VWAP[l]-df.High[l]), abs(df.VWAP[l]-df.Low[l])) <= myclosedistance):
     26             return 2
     27     if (df.VWAPSignal[l] == 1) and (min (abs(df.VWAP[l]-df.High[l]), abs(df.VWAP[l]-df.Low[l]))<=myclosedistance):

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __nonzero__(self)
   1532     @final
   1533     def __nonzero__(self):
-> 1534         raise ValueError(
   1535             f"The truth value of a {type(self).__name__} is ambiguous. "
   1536             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

There are some similar questions where the issue lies with the parenthesis around the if and statement. Have played around with it but cannot seem to get it right.


Solution

  • myclosedistance is a Series, so comparing against it results in a series. Maybe you meant this?

    myclosedistance = df['7Period-Range'][l]