【问题标题】:Using the column operator to check if pass or fail使用列运算符检查是否通过或失败
【发布时间】:2020-08-11 10:56:34
【问题描述】:

我不确定我是否可以使用操作符列来返回一个 pandas 系列,它将根据它的及格分数、操作符和实际值来确定某行的活动是通过还是失败。

数据集示例:

data={"ID": [1,1,2,2],
      "Activity": ["Quiz", "Attendance", "Quiz", "Attendance"],
      "Passing Score": [80, 2, 80, 2],
      "Operator": [">=", "<=", ">=", "<="],
      "Actual": [79, 0, 82, 3]
     }
data = pd.DataFrame(data)

它的样子:

ID  Activity    Passing Score   Operator    Actual
1   Quiz        80              >=          79
1   Attendance  2               <=          0
2   Quiz        80              >=          82
2   Attendance  2               <=          3

我的解决方案:

def score(pass_score, operator, actual):
    """
    pass_score: pandas Series, passing Score
    operator: pandas Series, operator
    actual: pandas Series, actual Score
    """
    
    the_list=[]
    
    for a,b,c in zip(pass_score, operator, actual):
        if b == ">=":
            the_list.append(c >= a)
        elif b == "<=":
            the_list.append(c <= a)
    
    mapper={True: "Pass",
            False: "Fail"
           }
    
    return pd.Series(the_list).map(mapper)

data["Peformance Tag"] = score(data["Passing Score"], data["Operator"], data["Actual"])

我想要实现的(如果可能的话,通过字典来缩短我的代码):

operator_map = {">=": >=,
                "<=": <=,
               }

data["Peformance Tag"] =  data[["Passing Score", "Operator", "Actual"]].apply(lambda x: x[0] operator_map[x[1]]  x[2], axis=1)

【问题讨论】:

    标签: python python-3.x pandas feature-engineering


    【解决方案1】:

    你可以这样做:

    data[['Passing Score', 'Operator', 'Actual']].astype(str).sum(axis=1).apply(eval)
    

    但说实话,我不会太相信这种编程。我觉得您的数据框可以通过 2 列以更有意义的方式重塑:

    • 实际测验
    • Actual_Attendance

    那么你可以这样做:

    data['Actual_quiz'] =< 80
    

    等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2015-12-17
      • 2011-10-13
      • 2019-03-07
      • 2017-02-14
      • 1970-01-01
      相关资源
      最近更新 更多