Inlie series of IFs present The truth value of a Series is ambiguous 错误

Inlie series of IFs present The truth value of a Series is ambiguous Error

我正在尝试根据一系列 if 条件在 Pandas DataFrame 中添加和填充一列。 我的代码看起来像这样

df['E'] = (('Text1;' if df['A'] else '') + ('Text2;' if df['B'] else '')) + ('Text3;' if df['C'] else '')

数据框看起来像

A       B        C        D
TRUE    FALSE    FALSE    4
FALSE   TRUE     TRUE     7
FALSE   FALSE    FALSE    1

编译器错误说真值不明确,我尝试按照 SO 的建议使用括号,但无法让它工作。

我已经围绕这个错误检查了许多其他关于 SO 的线程,但是 none 指出了这个问题。

谢谢

你的方法行不通,因为:if else with series and dfs is not good and there are many many QAs why it is wrong and what to do.

但你仍然可以在检查后尝试 np.select 2^3 种可能性,但你没有表现出这种尝试。

矩阵 mul 还有另一种方法:

#pd.Index plays better than list when it comes to @ below
texts = pd.Index(["Text1;", "Text2;","Text3;"])
#choose interested columns
columns = ["A","B","C"]
#perform matrix mult and assign
df["E"] = df[columns] @ texts

此处与@的矩阵乘法是“乘积之和”。它产生 3 个这样的总和,例如第一个 E 结果的 "Text1;" * True + "Text2;" * False + "Text3;" * False。这是您可能知道的常见矩阵乘法

df 变为

       A      B      C  D             E
0   True  False  False  4        Text1;
1  False   True   True  7  Text2;Text3;
2  False  False  False  1

2^3 方式 np.select。我们形成从 000 到 111

的“逻辑 table”
conditions = [
    ~df.A & ~df.B & ~df.C,
    ~df.A & ~df.B &  df.C,
    ~df.A &  df.B & ~df.C,
    ~df.A &  df.B &  df.C,
     df.A & ~df.B & ~df.C,
     df.A & ~df.B &  df.C,
     df.A &  df.B & ~df.C,
     df.A &  df.B &  df.C,
]

chooses = [
    "",
    "Text3;",
    "Text2;",
    "Text2;Text3;",
    "Text1;",
    "Text1;Text3;",
    "Text1;Text2;",
    "Text1;Text2;Text3;",
]

df["E"] = np.select(conditions,chooses)

df现在和上面一样