python - 嵌套 numpy.where 函数

标签 python pandas dataframe numpy

我将一些简单的数据框添加在一起,其中包含 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/

相关文章:

python - 有没有办法跨进程修补对象?

Python 3.4 CSV 使用 in 函数删除项目

python - 如何遍历各种训练和测试拆分

python - 每月为与客户关联的所有行分配正确的资格 - Python/Pandas

r - dplyr - 在嵌套列表中按元素汇总

python - 所有打印均带有选项卡。 Python

python - 在 python 中的字符串中使用冒号

python - 对第一列 pandas 数据帧的所有唯一值求和第二列值的正确方法

python - 为什么我的列不为空时显示为 NaN?

r - 根据R中的两列分配特定值