python - 使用 if-else 创建新列时 Pandas 出错 : The truth value of a Series is ambiguous

标签 python pandas

我正在使用 Pandas 并尝试使用 Python if-else 语句(又名三元条件运算符)创建一个新列以避免被零除。

例如,我想通过划分 A/B 来创建一个新列 C。我想使用 if-else 语句来避免除以 0。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=list('AB'))
df.head()
#    A  B
# 0  1  3
# 1  1  2
# 2  0  0
# 3  2  1
# 4  4  2

df['C'] = (df.A / df.B) if df.B > 0.0 else 0.0

但是,我从最后一行收到一个错误:

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

我在 StackOverflow 上搜索并找到了有关此错误的其他帖子,但都没有涉及此类 if-else 语句。一些帖子包括:

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

The truth value of a Series is ambiguous in dataframe

Error: The truth value of a Series is ambiguous - Python pandas

如有任何帮助,我们将不胜感激。

最佳答案

干什么

>>> df['C'] = np.where(df.B>0., df.A/df.B, 0.)

读作:

where df.B is strictly positive, return df.A/df.B, otherwise return 0.

关于python - 使用 if-else 创建新列时 Pandas 出错 : The truth value of a Series is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123368/

相关文章:

python - Django Admin - 通过模型过滤 ManyToManyField

python - 杀死多线程SocketServer

python - 如何在python中导入静态库?

python - numpy:将任意函数应用于数组元素

python - 如何从数据框( Pandas )打印特定值(字符串)的数据

python - 如何用点而不是条形图创建直方图

python - 从 python 执行时如何打印和捕获 7zip 的 % 进度标记?

python - Pandas 数据框中的新变量计算连续值

python - 根据条件拆分列值

python - 将多个虚拟变量转换为一列