Bio Bio - 4 months ago 11
Python Question

add one column (subtraction) to a dataframe with python

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

Answer

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