我正在使用 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, returndf.A/df.B
, otherwise return0.
关于python - 使用 if-else 创建新列时 Pandas 出错 : The truth value of a Series is ambiguous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123368/