我正在编写以下代码行:
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
语句,并且它工作得很好。不知道为什么它在那里可以工作,但在这里却不行。
最佳答案
首先,您需要删除多余的括号。因为它创建一个元组,并且您给 np.where 一个参数(元组),而不是三个参数。 这意味着该元组被解释为条件,因为第二个和第三个参数是可选的:
where(condition, [x, y])
Return elements, either from
x
ory
, depending oncondition
. If onlycondition
is given, returncondition.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)
关于python - np where 语句获取 : ValueError: The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48017236/