熊猫的真实价值观

发布于 2025-02-10 10:36:25 字数 930 浏览 1 评论 0原文

有人可以向我解释为什么括号是在熊猫中进行布尔比较所必需的吗?让我设置一家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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不念旧人 2025-02-17 10:36:25

检查更简单的表达将很有帮助。
将得分与5进行比较,给出了布尔值的系列,很棒。
如果我们投入布尔常数怎么办?

df.score >= 5 == True

是的,这是模棱两可的,请考虑使用.any()或.all()。

现在,为什么Python甚至首先支持这一点?
它反映了您在任何数学文本中找到的符号。
这样的紧凑表达可能非常有用:

if low <= 2 * value < high:

熊猫,其操作员覆盖了,
正在利用这种支持。

您还可以编写,如果a == b == c == d == e:
但这要少得多。

It would be helpful to examine a simpler expression.
Comparing score to 5 gives a Series of booleans, great.
What if we throw in a boolean constant?

df.score >= 5 == True

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:

if low <= 2 * value < high:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文