我将一些简单的数据框添加在一起,其中包含 1 列和 10 行。数据框中的每个元素可以是“1”、“0”或“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"])
这会生成一个由通过或失败值组成的数据帧。正是我想要的。然而有一个问题。当“P”出现在“criteria_1”总和中时,我希望它也出现在df[“criteria 1”]
中。
我试图添加一个额外的 numpy where 语句以将“p”放入 df["criteria 1"]
但出现错误。上面写着 “raise ValueError(f"No axis namenamed {axis} for object type {cls}")"
我尝试这样做时出现该错误:
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"))
如何将 df["criteria 1"] 设置为“通过”、“失败”和“P”的任何想法
最佳答案
IIUC,您可以使用np.select
如下:
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
从左到右查看条件列表,只要找到匹配项,它就会从选择列表中返回相应的值。如果不满足任何条件,则返回默认值,即此处的“Pass”
。
关于python - 嵌套 numpy.where 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67295499/