【问题标题】:Pandas, what is the difference between truth-values and ambiguous-truth-values? ValueError: The truth value of a Series is ambiguous熊猫,真值和模棱两可的真值有什么区别? ValueError: Series 的真值不明确
【发布时间】:2020-04-25 18:33:21
【问题描述】:

在 python 3. 中,使用库 pandas, 使用闲置代码时

    def check_question(df):
       mylambda = lambda x: x if x==x else x
       return df.apply(mylambda)

    print(check_question(df))

控制台给出了闲置的ValueError:

ValueError:Series 的真值不明确。使用 a.empty, a.bool()、a.item()、a.any() 或 a.all()

经过几次尝试,闲置的代码修复了它:

   def check_question(df):
       mylambda = lambda x: x if [x==x] else x
       return df.apply(mylambda)

    print(check_question(df))

我知道,和pandas库有关:Stackoverflow: The truth value of a Series is ambiguous

我意识到,当在 [] 之间进行封装时,表达式 x==x 值会从模棱两可的真实值变为真值。 我对它的含义有一个模糊的概念,但如果有人能启发我更多关于它的知识,我将不胜感激。

【问题讨论】:

  • 你真正想做什么?你有什么理由不直接使用.apply(lambda x: x)?
  • 表达式 x == x 输出 True,如果 x = x。如果我愿意,我可以写 x > 2,如果 x = 3,它将输出 True,但是对于 pandas,它会生成一个 ValueError,代码为 df.apply(lambda x: x if x>2 else x),(如果x>2 没有用 [] 封装)。这就是我想要表达的观点。表达式的布尔输出是我感兴趣的。与问题相关,lambda函数的返回输出是无关紧要的。

标签: python pandas


【解决方案1】:

您的第二个示例没有导致ValueError,因为您正在检查已定义的Python 列表(在本例中为[x == x])的真值。相反,Series 的真值是没有定义的(正如您所提到的)。

另见https://docs.python.org/3/library/stdtypes.html#truth-value-testing

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2022-09-28
    • 2020-08-03
    • 2019-12-19
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    相关资源
    最近更新 更多