首页 > 解决方案 > “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。但是,应该没关系。

标签: pythonpandas

解决方案


def function(x):

    all your conditions

    return status

dataframe["Calculated_status"] = dataframe.apply(function,axis=0)

这将完成这项工作,您现在要做的就是定义您的功能。

笔记

Python 不承认elseif 它被称为elif.


推荐阅读