首页 > 解决方案 > 对 Pandas 数据框的所有元素应用 if/then 条件

问题描述

我需要对 Pandas Dataframe 中的每个元素应用一个非常简单的 if/then 函数。

如果任何元素的值超过 0.5,我需要返回 1。否则,我需要返回 0。

使用 lambda 函数,这似乎非常简单,但每次我尝试时都会出错:'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()'

到目前为止,我有:

df_new = df.apply(lambda x: 1 if x > 0.5 else 1)

我会很感激任何帮助。

标签: pythonpandas

解决方案


您应该applymap改用,因为您希望对数据框中的每个元素执行操作,而不是对每一列执行操作,这就是这样apply做的。

df = pd.DataFrame({"A": [0.1, 0.2, 0.5, 0.6, 0.7],
                  "B": [0.75, 0.85, 0.2, 0.9, 0.0],
                  "C": [0.2, 0.51, 0.49, 0.3, 0.1]})

print(df)

      A        B       C
0   0.1     0.75    0.20
1   0.2     0.85    0.51
2   0.5     0.20    0.49
3   0.6     0.90    0.30
4   0.7     0.00    0.10

df_new = df.applymap(lambda x: 1 if x > 0.5 else 0)

print(df_new)

    A   B   C
0   0   1   0
1   0   1   1
2   0   0   0
3   1   1   0
4   1   0   0

推荐阅读