熊猫的真实价值观
有人可以向我解释为什么括号是在熊猫中进行布尔比较所必需的吗?让我设置一家MWE。
import pandas as pd
df = pd.DataFrame([["blue", 10], ["orange", 3], ["green", 7], ["red", 5]], columns = ["color", "score"])
结果框架:
color score
0 blue 10
1 orange 3
2 green 7
3 red 5
现在,我想比较一些真实价值。 但是,我可以
(df.score>=5) == (df.score>=5)
按照预期的方式跑步,
0 True
1 True
2 True
3 True
如果我跑步,
df.score>=5 == df.score>=5
我会得到
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python39\lib\site-packages\pandas\core\generic.py", line 1534, in __nonzero__
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
有关使比较成为可能的括号是什么?
Can someone explain to me why parentheses are necessary for boolean comparisons in pandas? Let me set up an MWE.
import pandas as pd
df = pd.DataFrame([["blue", 10], ["orange", 3], ["green", 7], ["red", 5]], columns = ["color", "score"])
The resulting dataframe:
color score
0 blue 10
1 orange 3
2 green 7
3 red 5
Now, I would like to compare some truth values. I can run
(df.score>=5) == (df.score>=5)
which gives, as expected,
0 True
1 True
2 True
3 True
However, if I instead run
df.score>=5 == df.score>=5
I get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python39\lib\site-packages\pandas\core\generic.py", line 1534, in __nonzero__
raise ValueError(
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
What is it about the parentheses that makes the comparison possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查更简单的表达将很有帮助。
将得分与
5
进行比较,给出了布尔值的系列
,很棒。如果我们投入布尔常数怎么办?
是的,这是模棱两可的,请考虑使用.any()或.all()。
现在,为什么Python甚至首先支持这一点?
它反映了您在任何数学文本中找到的符号。
这样的紧凑表达可能非常有用:
熊猫,其操作员覆盖了,
正在利用这种支持。
您还可以编写
,如果a == b == c == d == e:
,但这要少得多。
It would be helpful to examine a simpler expression.
Comparing score to
5
gives aSeries
of booleans, great.What if we throw in a boolean constant?
Right, it's ambiguous, consider using .any() or .all().
Now, why does python even support that in the first place?
It mirrors the notation you'll find in any math text.
A compact expression like this can be quite useful:
and pandas, with its operator overrides,
is leveraging such support.
You can also write
if a == b == c == d == e:
,but that comes up much less often.