nesting numpy.where functions

Viewed 45

I am adding a few simple data frames together consisting of 1 column and 10 rows. each element in the dataframe can be "1", "0" or "P"

criteria_1 = df['c1] + df['c2'] + df['c3] + df['c4']
criteria_1_mapped = criteria_1.map(lambda x: 'P' if 'P' in x else sum(map(int, list(x))))
df["criteria 1"] = np.where(criteria_1_mapped == 4, "Fail", "Pass")
print(df["criteria 1"])

This produce a dataframe that consists of pass or fail values. Exactly as i want. however there is a problem. When a "P" appears in "criteria_1" sum i want it to appear in df["criteria 1"] as well.

i am trying to add in an additional numpy where statement to put a "p" in df["criteria 1"] but i get an error. that says "raise ValueError(f"No axis named {axis} for object type {cls}")"

that error appears the i try to do this:

criteria_1 = df['c1] + df['c2'] + df['c3] + df['c4']
criteria_1_mapped = criteria_1.map(lambda x: 'P' if 'P' in x else sum(map(int, list(x))))
is_P_in_dataframe = (criteria_1_mapped == "P").any(axis=1)
df["criteria 1"] = np.where(is_P_in_dataframe, "P", np.where(criteria_1_mapped == 4, "Fail", "Pass"))

Any ideas how I can set df["criteria 1"] to have "Pass", "Fail" and "P"

1 Answers

IIUC, you can use np.select as follows:

cond_list = [criteria_1_mapped.str.contains("P"), criteria_1_mapped == 4]
choice_list = ["P", "Fail"]
default = "Pass"

df["criteria_1"] = np.select(cond_list, choice_list, default=default)

np.select looks at the condition list from left to right and wherever it finds a match, it returns the corresponding value from the choice list. If no condition is satisifed, it returns the default value i.e., "Pass" here.

Related