我在使用 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
提前感谢任何帮助。
Series
对象的问题。 - Daniel Rosemanpnl[company].tail(1)['Active'].any()==1
,即使这仍然是单个值。 - EdChum