[英]How to compare two cells in a given DataFrame in pandas Python 2.7
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: 现在我去ipython termnal并输入:
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: 但是当我去我的IPython(或我的编辑Spyder)和代码时:
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? 有什么方法可以解决这个变通方法并直接比较DataFrame中的两个单元格吗?
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, ie 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. 当你比较两个系列时,你会得到另一个系列,你不能直接在if语句中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.