【发布时间】:2014-06-21 02:34:28
【问题描述】:
我在使用 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对象的问题。 -
这似乎是您正在使用的 pandas 库所特有的。看起来 pandas 提供的对象有点像字典,但在重要方面有所不同。需要明确的是,您在这里处理的不是通常的 Python 字典,而是使用 pandas 提供的具有类字典语法的数据结构。
-
你产生一个系列而不是字典,因此它无法评估你的布尔查询,就像错误建议你需要做
pnl[company].tail(1)['Active'].any()==1,即使这仍然是一个单一的值 -
关于您的第二个问题,您是否混淆了序数输出数?所以如果你只是反复打印“yay”或print(“yay”)(对于python 3),这个数字仍然会增加
-
@neanderslob:事实上,您从 pandas 库源文件中收到了诸如
The truth value of a Series is ambiguous之类的错误。
标签: python pandas if-statement series