【问题标题】:np where statement gets: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()np where 语句得到:ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
【发布时间】:2018-06-09 13:51:51
【问题描述】:

我正在为以下代码行编写:

holiday['real_or_not'] = np.where((holiday['transferred']=='False',1,0))
holiday

最小可重现示例:

date        type   locale    locale_name  description    transferred

2012-03-02  False  locale     Manta        Fundacion de Manta  False
2012-03-02  False  Regional   Regional     Gunanta              True

我得到:

ValueError: The truth value of a Series is ambiguous. Use a.empty,a.bool(), a.item(), a.any() or a.all().

任何想法为什么?我在我的代码中在不同的 pandas 数据帧上写了一个非常相似的 np.where 语句,它工作得非常好。不知道为什么它会在那里工作,但在这里却不行。

【问题讨论】:

  • 您能否展示您的数据样本,以便我尝试重现此内容?
  • @MadPhysicist 是的,我刚刚添加了
  • np.where((...)) 双括号是故意的吗?
  • @mkheifetz 我会让其他熟悉 numpy 并能准确解释发生了什么的人回答。我只是觉得双括号看起来很可疑。
  • 不知道为什么您需要np.where 来获取简单的 0/1。请改用.astype(int)

标签: python python-2.7 pandas numpy where


【解决方案1】:

首先,您需要删除多余的括号。因为它创建了一个元组,你给np.where 一个参数,元组,而不是三个参数。 这意味着这个元组被解释为条件,因为第二个和第三个参数是可选的:

where(condition, [x, y]) 

xy 返回元素,具体取决于condition。 如果只给出condition,则返回condition.nonzero()

仅使用一个参数调用函数,您可以添加任意数量的额外括号。一旦你添加了一个逗号,你就创建了一个元组,你不能再这样做了,除非你改变参数被赋予函数的方式。

假设transferred 列是bool,你可以颠倒你的逻辑:

holiday['real_or_not'] = np.where(holiday['transferred'], 0, 1)

结果:

             type    locale locale_name description  transferred  real_or_not
date                                                                         
2012-03-02  False    locale       Manta   Fundacion        False            1
2012-03-02  False  Regional    Regional     Gunanta         True            0

没有np.where的替代解决方案:

holiday['real_or_not'] = (~holiday.transferred).astype(int)

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2016-12-01
    • 2019-01-24
    • 2020-05-27
    • 1970-01-01
    • 2021-03-21
    • 2021-05-27
    • 2021-04-07
    • 2022-12-29
    相关资源
    最近更新 更多