将 if-else 函数应用于数据框中的每个单元格会导致不明确的异常

Apply if-else function to each cell in a dataframe results in ambiguous exception

我有一个 pandas dataframe 这样的:

index a b c
1 1 12 15
2 5 15 16

列数和列名可以是可变的,但它始终包含一个数值。我想用 -101 替换值,具体取决于值和一些阈值(lowhigh)。

我考虑过定义一个 lambda 函数并只使用 apply

df.apply(lambda x: -1 if x < low else (1 if x > high else 0))

但由于以下异常,这不起作用:

'The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().'

我不太确定为什么会发生这种情况以及什么是最好的(也与性能有关)解决方案。欢迎任何 advice/help。

您正在向 lambda 发送完整的数据帧,但您需要向它发送一列:

for col in df.columns:
    df[col].apply(lambda x: -1 if x < low else (1 if x > high else 0))

您正在寻找的是 pandas.DataFrame.applymap,它按元素应用函数:

df.applymap(lambda x: -1 if x < low else (1 if x > high else 0))

方法 pandas.DataFrame.apply 沿给定轴应用函数(默认为按列)。