1

enter image description hereI want to compare 2 columns using the following if else condition and update a value in the new column using some formula.

if df.loc[df['TF'] < df['PV']]:
    df['Par_2']] = 0.01*(1.8 * df['PV'] + 32) - 2
elif(some other condition)

While I execute this I get the following error

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Can any one help what can I do to resolve this error. Or is there any other way to compare 2 columns and insert a new column whose value is calculation involving some other columns as shown above.

ruths32
  • 11
  • 1
  • 3
  • please show an example of your dataframe and your expected output – ansev Nov 17 '19 at 13:46
  • Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – Guy Nov 17 '19 at 13:47
  • Comparing two vectors (columns in a dataframe) returns a vector. You can't ask if True on a vector of boolean values. – Josh Friedlander Nov 17 '19 at 13:55
  • Here is the expected output. Par_2 is the newly calculated column – ruths32 Nov 17 '19 at 14:00
  • @ansev Have added the expected output format – ruths32 Nov 17 '19 at 14:07
  • @JoshFriedlander Then Can you suggest how can I insert a new column based on the condition I mentioned – ruths32 Nov 17 '19 at 14:08
  • please check my answer, in the `'enter here second formule'` you need put your other formule for the elif condition – ansev Nov 17 '19 at 14:17
  • @ansev Thank you. But I have total 3 conditions. I doubt if i can write all 3 in the same where clause. – ruths32 Nov 17 '19 at 14:25
  • please check now and consider accept https://stackoverflow.com/help/someone-answers – ansev Nov 17 '19 at 14:33

1 Answers1

1

Use np.where:

df['Par_2']=np.where(df['TF'] < df['PV'], 0.01*(1.8 * df['PV'] + 32) - 2,  'enter here sencond formule')

or numpy.select:

conditions=[df['TF'] < df['PV'],df['TF'] == df['PV'],df['TF'] > df['PV']] #for example
values=[0.01*(1.8 * df['PV'] + 32) - 2, 7, 10] #for example
df['Par_2']=np.select(conditions,values)
ansev
  • 30,322
  • 5
  • 17
  • 31
  • Thank you @ansev. But I have total 3 condition. I doubt if i can write all 3 in the same where clause. – ruths32 Nov 17 '19 at 14:20