【发布时间】:2021-06-23 06:16:26
【问题描述】:
问题
我正在尝试使用 if 语句 (np.where) 比较两列中的值,但是我不断收到错误消息。我无法弄清楚为什么,我以前在数据框中使用 np.where 没有问题。
ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。
示例
df = pd.DataFrame(
{'colors': ['red', 'white', 'blue'],
'n1': [1, 2, 3],
'n2': [4, 6, 7],
'n3': [5, 3, 2]
}
)
df['test'] = np.where(
df.n1 > df.n2,
max(0, df.n1 - df.n3),
df.n3
)
错误信息
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/project/example.py", line 15, in <module>
df['test'] = np.where(df.n1 > df.n2, max(0, df.n1 - df.n3), df.n3)
File "C:\Users\user\Continuum\anaconda3\envs\CondaEnv\lib\site-packages\pandas\core\generic.py", line 1442, in __nonzero__
f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Process finished with exit code 1
非常感谢任何帮助。
【问题讨论】: