1

This is the code I have written and df is dataframe. I am using python3 and I am new to pandas and I have tried bitwise operator as well as keywords and or

if((df['Day_Perc_Change']>=-0.5) & (df['Day_Perc_Change']<=0.5)):

    df['Trend']="Slight or No Change"

elif((df['Day_Perc_Change']>=0.5) & (df['Day_Perc_Change']<=1)):

    df['Trend']="Slight Positive"

elif((df['Day_Perc_Change']>=-1) & (df['Day_Perc_Change']<=-0.5)):

    df['Trend']="Slight Negative"

elif((df['Day_Perc_Change']>=1) & (df['Day_Perc_Change']<=3)):

    df['Trend']="Positive"

elif((df['Day_Perc_Change']>=-3) & (df['Day_Perc_Change']<=-1)):

    df['Trend']="Negative"

elif((df['Day_Perc_Change']>=3) & (df['Day_Perc_Change']<=7)):

    df['Trend']='Among top gainers'

else:

    df['Trend']="Bear drop"
}

**This is the error I am getting

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
 I have used both and as well as | but it is working.
Can anyone help me out?
​**
Aniket
  • 11
  • 1
  • 1
    Does https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o help? – Karl Knechtel Jun 06 '20 at 20:33
  • Does this answer your question? [Pandas error when using if-else to create new column: The truth value of a Series is ambiguous](https://stackoverflow.com/questions/48123368/pandas-error-when-using-if-else-to-create-new-column-the-truth-value-of-a-serie) – avocadoLambda Jun 07 '20 at 00:17

1 Answers1

0

BAM, np.where(), which is also vectorized and high-performing.

df['Trend'] = ''
df['Trend'] = np.where((df['Day_Perc_Change']>=-0.5) & (df['Day_Perc_Change']<=0.5), "Slight or No Change", df['Trend'])
df['Trend'] = np.where((df['Day_Perc_Change']>=0.5) & (df['Day_Perc_Change']<=1), "Slight Positive", df['Trend'])
df['Trend'] = np.where((df['Day_Perc_Change']>=-1) & (df['Day_Perc_Change']<=-0.5), "Slight Negative", df['Trend'])
df['Trend'] = np.where((df['Day_Perc_Change']>=1) & (df['Day_Perc_Change']<=3), "Positive", df['Trend'])
df['Trend'] = np.where((df['Day_Perc_Change']>=-3) & (df['Day_Perc_Change']<=-1), "Negative", df['Trend'])
df['Trend'] = np.where((df['Day_Perc_Change']>=3) & (df['Day_Perc_Change']<=7), "Among top gainers", df['Trend'])
David Erickson
  • 16,433
  • 2
  • 19
  • 35