Reputation: 239
This is the code that I am using.
from datetime import date, datetime, timedelta
import pandas_datareader.data as web
todays_date = date.today()
n = 30
date_n_days_ago = date.today() - timedelta(days=n)
stock_data = web.DataReader('ACC.NS', 'yahoo', date_n_days_ago, todays_date)
stock_data = stock_data[stock_data.Volume != 0].tail(20)
stock_data = stock_data[['Adj Close']]
Now I go to ipython termnal and type:
stock_data['Adj Close'].iloc[[19]] > stock_data['Adj Close'].iloc[[0]]
then the output I get is:
Date
2016-02-18 True
But when I go to my IPython (or my editor Spyder) and code:
if stock_data['Adj Close'].iloc[[19]] > stock_data['Adj Close'].iloc[[0]]:
print " greater"
the output I get is:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
MY DOUBT: Why does this happen ?
Presently I have found a workaround code:
adj_close_list = stock_data.values.T.tolist()
if adj_close_list[0][19] > adj_close_list[0][0]:
print "greater"
else:
print "less"
Is there any way I can do away with this workaround and directly compare two cells in a DataFrame?
Upvotes: 3
Views: 963
Reputation: 85562
Remove the extra []
:
if stock_data['Adj Close'].iloc[19] > stock_data['Adj Close'].iloc[0]:
print('greater')
else:
print('less')
This gives you a float, i.e. a cell:
>>> stock_data['Adj Close'].iloc[19]
1256.3499999999999
But this gives you a series:
>>> stock_data['Adj Close'].iloc[[19]]
Date
2016-02-18 1.256E+03
Name: Adj Close, dtype: float64
When you compare two series you get another series, which you cannot use in an if statement directly.
Upvotes: 1