我正在使用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语句。一些帖子包括:
系列的真值含糊不清。使用a.empty,a.bool(),a.item(),a.any()或a.all()
任何帮助,将不胜感激。
df.B > 0
产生系列,例如:
0 True # 4 > 0 => True
1 True # 2 > 0 => True
2 True # ...
3 True
4 True
5 True
6 True
7 True
8 False # 0 is not > 0 => False
9 False # 0 is not > 0 => False
...
返回多个值会导致歧义(一些为True,另一些为False)。
一种解决方案是使用np.where
:
sentinel = np.nan # Or 0 if you must...
df = df.assign(C=np.where(df['B'] != 0, df['A'] / df['B'], sentinel))
>>> df
A B C
0 2 4 0.5
1 0 2 0.0
2 1 2 0.5
3 4 4 1.0
4 1 1 1.0
5 4 4 1.0
6 2 4 0.5
7 1 2 0.5
8 4 0 NaN # NaN is assigned in cases where the value in Column `B` is zero.
9 1 0 NaN
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句