1
votes

I try to add one column in a dataframe df2 which contains the value 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']) 

I got this error message :

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().

Any idea please?

Thank you

2

2 Answers

1
votes

IIUC:

df2['depassement'] = df2['P_ACT_KW'] - df2['P_SOUSCR']
df2[df2['depassement'] < 0, 'depassement'] = 0

This should also work:

df2['depassement'] = df2.P_ACT_KW.sub(df2.P_SOUSCR).apply(lambda x: max(x, 0))
0
votes

You need to do:

df2['depassement'] = np.where((df2['P_ACT_KW'] - df2['P_SOUSCR']) < 0), 0, df2['P_ACT_KW'] - df2['P_SOUSCR']) 

if doesn't understand how to compare array like structures hence the error, here we can use np.where to compare all rows to produce a mask and where the condition is true set to 0 else perform the subtraction