Reputation: 3
I have a pandas series as shown
I want to compare the value of the last two rows "Total" and "SMA20" to perform an action. (Please note the Pandas dataframe is large, Im pasting only last row)
myData = {'Date':[2022-01-17 15:27:00+05:30], 'total': [200],
'20SMA': [220]
}
I tried to store them in two separate variables by doing below
last_sma = myData['SMA20'].iloc[-1:]
last_total = myData['Total'].iloc[-1:]
Then try comparing both of the them,
if last_sma > last_total:
print('SMA is large')
I get the below error.
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
When I try see the variable content its shown as below
Date 2022-01-17 15:27:00+05:30 215.155 Name: SMA20, dtype: float64
Its pandas series
Upvotes: 0
Views: 840
Reputation: 822
Welcome on Stackoverflow!
What you are getting with the way you make your slices are pandas Series
last_sma = myData['SMA20'].iloc[-1:] # last_sma is a single value Series
last_total = myData['Total'].iloc[-1:] # last_total is a single value Series
myData['SMA20']
returns a Series
which holds the data from column SMA20
, and the .iloc[-1:]
returns a slice of this Series
, with only one record, but a Series
nonetheless.
Comparing 2 series with >
operator returns another Series
, holding the true of false value for comparison for each pair of records. In your, case it holds a Series with a single true or false value.
As stated by the error message you get, trying to collapse a Series
of boolean values into a single boolean value is not well defined - even if your Series
holds a single record.
If you only need to compare the last value, a simple way to make your code work is to remove the :
in your slices.
last_sma = myData['SMA20'].iloc[-1] # returns the single value at location -1
last_total = myData['Total'].iloc[-1] # returns the single value at location -1
if last_sma > last_total:
print('SMA is large') # should work now!
Upvotes: 1