当我对数据框中的单个元素进行比较时出现错误,但我不明白为什么。
我有一个数据框 df,其中包含许多客户的时间序列数据,其中包含一些空值:
df.head()
8143511 8145987 8145997 8146001 8146235 8147611 \
2012-07-01 00:00:00 NaN NaN NaN NaN NaN NaN
2012-07-01 00:30:00 0.089 NaN 0.281 0.126 0.190 0.500
2012-07-01 01:00:00 0.090 NaN 0.323 0.141 0.135 0.453
2012-07-01 01:30:00 0.061 NaN 0.278 0.097 0.093 0.424
2012-07-01 02:00:00 0.052 NaN 0.278 0.158 0.170 0.462
在我的脚本中,行 if pd.isnull(df[[customer_ID]].loc[ts]): 产生错误:
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
但是,如果我在脚本行放置一个断点,当脚本停止时,我在控制台中输入:
pd.isnull(df[[customer_ID]].loc[ts])
输出是:
8143511 True
Name: 2012-07-01 00:00:00, dtype: bool
如果我允许脚本从该点继续,则会立即生成错误。
如果 boolean 表达式可以求值并且值为 True,为什么它会在 if 表达式中产生错误?这对我来说毫无意义。
请您参考如下方法:
问题出在if语句上。
当你写代码的时候
if this:
print(that)
this 将被评估为 bool(this)。最好返回 True 或 False。
但是,你做到了:
if pd.isnull(df[[customer_ID]].loc[ts]):
pass # idk what you did here because you didn't say... but doesn't matter
此外,您声明 pd.isnull(df[[customer_ID]].loc[ts]) 评估为:
8143511 True
Name: 2012-07-01 00:00:00, dtype: bool
这看起来像 True 还是 False?
bool(pd.isnull(df[[customer_ID]].loc[ts])) 怎么样?
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
所以教训是:pd.Series 不能评估为 True 或 False
但是,它是 True 和 False 的 pd.Series。
这就是它不起作用的原因。
