我尝试在数据帧 df2 中添加一列,其中包含值 0 if(df2['P_ACT_KW'] - df2['P_SOUSCR']) < 0 else df2['P_ACT_KW']- df2['P_SOUSCR']
.
if (df2['P_ACT_KW'] - df2['P_SOUSCR']) <0:
df2['depassement']=0
else:
df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSCR'])
我收到此错误消息:
ValueError Traceback (most recent call last) in () ----> 1 if (df2['P_ACT_KW'] - df2['P_SOUSCR']) <0: 2 df2['depassement']=0 3 else: 4 df2['depassement']= (df2['P_ACT_KW'] - df2['P_SOUSCR'])
C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py in nonzero(self) 890 raise ValueError("The truth value of a {0} is ambiguous. " 891 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." --> 892 .format(self.class.name)) 893 894 bool = nonzero
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
请问有什么想法吗?
谢谢
最佳答案
IIUC:
df2['depassement'] = df2['P_ACT_KW'] - df2['P_SOUSCR']
df2[df2['depassement'] < 0, 'depassement'] = 0
这也应该有效:
df2['depassement'] = df2.P_ACT_KW.sub(df2.P_SOUSCR).apply(lambda x: max(x, 0))
关于python - 使用 python 将一列(减法)添加到数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38638199/