Search code examples
pythonpython-3.xpandasfeature-engineering

Using the column operator to check if pass or fail


I'm not sure if how can I use the operators column for me to return a pandas series where it will determine if a certain row's activity will pass or fail based from it's passing score, operator and actual.

Dataset Sample:

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)

What it looks like:

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

My Solution:

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"])

What I want to achieve (which is to shorten my code by using dictionary, if it is possible):

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

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

Solution

  • You can do:

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

    But to tell you the truth I will not trust this kind of programming too much. I have the feeling that your dataframe can be reshaped in a more meaningful way by having 2 columns:

    • Actual_quiz
    • Actual_Attendance

    Then you can do:

    data['Actual_quiz'] =< 80
    

    and so on.