Python error: ValueError: The truth value of a Series is ambiguous

python
#1

Hi,

I’m trying to perform boolean indexing a series using values of other series of same length. This problem can be replicated using the code:

x = pd.Series([1,2,3])
y = pd.Series(x, copy=True)
print y[(x>1) or (x<=1)]

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

If I use simply print x[x>1] it works fine. Not sure why it doesn’t work with the “or” operator.

Please help.

Regards,
Aarshay

#2

Hi @Aarshay,

Boolean indexing in pandas is a little different than normal python indexing.

The correct way to implement it would be;

print y[(x>1) | (x<=1)]

Note: This is for pandas version 18.1, may not be the same in later versions. Check reference here

#3

Thanks @jalFaizy for your response. It works!

#4

ValueError Traceback (most recent call last)
in
1 fit1 = Holt(data).fit(smoothing_level=0.8, smoothing_slope=0.2, optimized=False)
2 fcast1 = fit1.forecast(5).rename(“Holt’s linear trend”)
----> 3 fit2 = Holt(data, exponential=True).fit(smoothing_level=0.8, smoothing_slope=0.2, optimized=False)
4 fcast2 = fit2.forecast(5).rename(“Exponential trend”)
5 fit3 = Holt(data, damped=True).fit(smoothing_level=0.8, smoothing_slope=0.2)

/anaconda3/lib/python3.7/site-packages/statsmodels/tsa/holtwinters.py in init(self, endog, exponential, damped)
851 def init(self, endog, exponential=False, damped=False):
852 trend = ‘mul’ if exponential else ‘add’
–> 853 super(Holt, self).init(endog, trend=trend, damped=damped)
854
855 def fit(self, smoothing_level=None, smoothing_slope=None, damping_slope=None, optimized=True):

/anaconda3/lib/python3.7/site-packages/statsmodels/tsa/holtwinters.py in init(self, endog, trend, damped, seasonal, seasonal_periods, dates, freq, missing)
389 self.trending = trend in [‘mul’, ‘add’]
390 self.seasoning = seasonal in [‘mul’, ‘add’]
–> 391 if (self.trend == ‘mul’ or self.seasonal == ‘mul’) and (endog <= 0.0).any():
392 raise NotImplementedError(
393 ‘Unable to correct for negative or zero values’)

/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in nonzero(self)
1574 raise ValueError("The truth value of a {0} is ambiguous. "
1575 “Use a.empty, a.bool(), a.item(), a.any() or a.all().”
-> 1576 .format(self.class.name))
1577
1578 bool = nonzero

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

Please help in this respect