使用逻辑表达式和if语句评估熊猫系列值
问题内容:
我在使用if语句评估字典中的值时遇到麻烦。
给定以下字典,我从一个数据框中导入了它(以防万一):
>>> pnl[company]
29: Active Credit Date Debit Strike Type
0 1 0 2013-01-08 2.3265 21.15 Put
1 0 0 2012-11-26 40 80 Put
2 0 0 2012-11-26 400 80 Put
我试图评估以下陈述来确定最后一个值的值Active
:
if pnl[company].tail(1)['Active']==1:
print 'yay'
但是,我遇到了以下错误消息:
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
if pnl[company].tail(1)['Active']==1:
File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 676, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
鉴于我可以使用上述命令而不使用if语句来显示所需的值,这使我感到惊讶:
>>> pnl[company].tail(1)['Active']
30: 2 0
Name: Active, dtype: object
鉴于该值显然为零且索引为2,因此我尝试了以下操作进行简短的健全性检查,结果发现事情并没有像我预期的那样发生:
>>> if pnl[company]['Active'][2]==0:
... print 'woo-hoo'
... else:
... print 'doh'
doh
我的问题是:
1)这可能是怎么回事?我怀疑我在某些基本层面上误解了字典。
2)我注意到当调出该字典的任何给定值时,左侧的数字增加1。这代表什么?例如:
>>> pnl[company].tail(1)['Active']
31: 2 0
Name: Active, dtype: object
>>> pnl[company].tail(1)['Active']
32: 2 0
Name: Active, dtype: object
>>> pnl[company].tail(1)['Active']
33: 2 0
Name: Active, dtype: object
>>> pnl[company].tail(1)['Active']
34: 2 0
Name: Active, dtype: object
在此先感谢您的帮助。
问题答案:
您产生的是一个Pandas Series对象,即使您只是将值更改为以下值,也无法以您尝试的方式对其进行评估:
if pnl[company].tail(1)['Active'].any()==1:
print 'yay'
关于第二个问题,请参阅我的评论。
编辑
从注释和链接到输出,调用any()
修复了错误消息,但是您的数据实际上是字符串,因此比较仍然失败,您可以执行以下操作:
if pnl[company].tail(1)['Active'].any()=='1':
print 'yay'
进行字符串比较,或修复读取或生成的数据。
或执行:
pnl['Company']['Active'] = pnl['Company']['Active'].astype(int)
转换dtype
列的,以便您的比较更加正确。