python - “ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。” 在嵌套 if python 和 pandas
问题描述
我有一个熊猫数据框“positions_deposits”:
+------------+-----------------+----------------+-- --------------+--------+ | 参数 | 琥珀阈值 | 红色阈值 | 类型阈值 | 价值观 | +------------+-----------------+----------------+-- --------------+--------+ | 参数1 | 10 | 5 | 减 | 7 | | 参数2 | 50 | 100 | 更多 | 200 | | 参数1 | 10 | 5 | 减 | 60 | | 参数2 | 50 | 100 | 更多 | 10 | +------------+-----------------+----------------+-- --------------+--------+
如果难以阅读,请将数据作为纯文本粘贴到此处(stackoverflow 的新手,抱歉 :(
Parameter Amber_threshold Red_threshold Type_threshold Values
Parameter1 10 5 Less 7
Parameter2 50 100 More 200
Parameter1 10 5 Less 60
Parameter2 50 100 More 10
我想创建另一列,Calculated_status,其值将是“Green”、“Amber”或“Red”,具体取决于以下逻辑:
def RAG_function (Amber_threshold, Red_threshold, Type_threshold, Values):
if Type_threshold == 'Less':
if Values <= Red_threshold:
Status = 'Red'
elif Values <=Amber_threshold:
Status = 'Amber'
else: Status = 'Green'
if Type_threshold == 'More':
if Values > Red_threshold:
Status = 'Red'
elif Values > Amber_threshold:
Status = 'Amber'
else: Status = 'Green'
return Status
例如,在上述表格中,Calculated_status 将分别为“Amber”、“Red”、“Green”和“Green”。
调用函数为:
positions_deposits['Calculated_status'] = positions_deposits.apply(RAG_function(positions_deposits['Amber_threshold'], positions_deposits['Red_threshold'], positions_deposits['Type_threshold'], positions_deposits['Values']), axis =0)
我收到以下错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我究竟做错了什么?顺便说一句,我正在使用整个东西streamlit
。但是,应该没关系。
解决方案
def function(x):
all your conditions
return status
dataframe["Calculated_status"] = dataframe.apply(function,axis=0)
这将完成这项工作,您现在要做的就是定义您的功能。
笔记
Python 不承认elseif
它被称为elif
.
推荐阅读
- python - 如何在不注册视图的情况下将 Scala DataFrame 引入 Python,反之亦然?
- sql - MsSql FUNCTION 和 WHERE
- java - 如何让java执行器具有相同的线程?
- cross-browser - 试图在不同的浏览器中找到工具提示的最大长度
- linker - 绑定 MvvmCross TextColor 不适用于 Android
- powershell - 将命令传递给 Argument-List 中的 powershell start-Process
- android - 模块 react-native-fs 和 rn-fetch-blob 的 React Native 构建失败
- modelica - 如何在 Modelica 中使用模型中的单位属性?
- wordpress - 将媒体附件放在其他目录中(Wordpress)
- javascript - 每个 then() 应该返回一个值或抛出 - 节点 JavaScript 中的 promise/always-return