在熊猫数据框的所有元素上应用if / then条件

时间:2020-09-01 20:08:13

标签: python pandas

我需要对熊猫数据框中的每个元素应用非常简单的if / then函数。

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

使用lambda函数,这看起来真的很简单,但是每次尝试时,我都会收到错误消息:web: daphne project.asgi:application --port $PORT --bind 0.0.0.0

到目前为止,我有:

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您应该改用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

答案 1 :(得分:1)

如果它是二进制文件,则可以使用以下内容:

df = (df > 0.5).astype(int)

括号中的代码将生成布尔数据框,然后将其转换为整数1和0(1表示True,0表示False)