【发布时间】:2018-01-06 01:14:27
【问题描述】:
我正在使用 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
任何帮助将不胜感激。
【问题讨论】: