【问题标题】:"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()." in nested if python and pandas“ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”在嵌套 if python 和 pandas
【发布时间】:2020-11-26 00:21:11
【问题描述】:

我有一个熊猫数据框,“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。但是,应该没关系。

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    def function(x):
    
        all your conditions
    
        return status
    
    dataframe["Calculated_status"] = dataframe.apply(function,axis=0)
    

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

    注意

    Python 无法识别 elseif,它被称为 elif

    【讨论】:

    • 在遵循您的指导后,我已根据我的观察更新了问题。它给了我一个上面更新的错误。你能帮忙吗?
    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 2016-12-01
    • 2020-02-12
    • 2021-08-14
    • 2020-05-27
    • 2021-09-15
    • 2018-11-22
    • 2021-03-21
    相关资源
    最近更新 更多