1

I am using if condition in python to perform a calculation but I am getting The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). error

Can someone please help me in understanding how to perform actions on a dataframe based on if condition on other columns?

if (simulated_hour['Weeknnd'] == 'Weekday'):
    simulated_hour['simulated'] = simulated_hour['Forecast_call']*simulation_weekday
    simulated_hour

Attached is the image of the code and error

enter image description here

SMR
  • 401
  • 4
  • 15

2 Answers2

2

The message if self-explanatory. Since simulated_hour['Weeknnd'] is not a single value, the term simulated_hour['Weeknnd'] == 'Weekday' might be true for some values and false for others. So, use (...).any() or (...).all() depending on whether you want at least one or all of the values to be true.

blue_note
  • 27,712
  • 9
  • 72
  • 90
1

You can achieve what you want with the following code snippet:

simulated_hour.loc[simulated_hour['Weeknnd'] == 'Weekday', 'simulated'] = simulated_hour.loc[simulated_hour['Weeknnd'] == 'Weekday', 'Forecast_call']*simulation_weekday

Pandas has it's own query syntax, since you can't use simple if statements to make selections like you've mentioned.

If you're familiar with SQL, the following state could be helpful in understanding the basis: https://pandas.pydata.org/docs/getting_started/comparison/comparison_with_sql.html

Punker
  • 1,770
  • 9
  • 16