【发布时间】:2020-07-16 22:22:13
【问题描述】:
我有一个如下所示的数据框:
col1 col2
0 abc 0
1 def -1
2 ghi 1
3 jkl -0.5
再现:
data = {'col1': ['abc', 'def','ghi','jkl'],
'col2': ['0', '-1','1','-0.5']
}
df = pd.DataFrame (data, columns = ['col1','col2'])
我想添加第三列,其内容基于 col2 的条件评估 所以结果如下:
col1 col2 col3
0 abc 0 blue
1 def -1 red
2 ghi 1 green
3 jkl -0.5 red
我当前的代码是这样的:
df['col3'] = np.where((df['col2'] >=1,'green',
(df['col2'] ==0, 'blue',
(df['col2'] <0, 'red'))))
但是,这目前失败并出现以下错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-151-a19019bc0d01> in <module>
1 df['col3'] = np.where((df['col2'] >=1,'green',
2 (df['col2'] ==0, 'blue',
----> 3 (df['col2'] <0, 'red'))))
//anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
1476 raise ValueError("The truth value of a {0} is ambiguous. "
1477 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1478 .format(self.__class__.__name__))
1479
1480 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
能否请您解释错误并建议我如何实现最终目标?
谢谢
【问题讨论】:
-
你没有遵循
where的语法。
标签: python-3.x numpy jupyter-notebook conditional-statements where-clause