0

I am Currently trying to create IF statements to apply a class element to certain cells so I can style them using CSS. I currently can't use the styling options that pandas gives because I am using the .to_html function.

My table is as follows. {'Pwer':[-.3,-1.3,-2.4], 'Trend':[1.3,-1.3,-1.7]}

I tried

if((hist['Pwer']<0) & (hist['Trend']<0)):
            hist['Pwer']=hist['Pwer'].apply(lambda x:'<span class="Negative Trend_neg">{0}</span>'.format(x))

But it results in

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

I'm not quite sure I understand what is going on even if I apply .all() to both hist['Pwer'] and hist['Trend']. Any help would be appreciative.

2 Answers 2

1

Something like this will work:

cond =  ((hist['Pwer']<0) & (hist['Trend']<0))
hist['Pwer'][cond] = hist['Pwer'][cond].apply(lambda x:'<span class="Negative Trend_neg">{0}</span>'.format(x))

The output is

                                           Pwer  Trend
0                                          -0.3    1.3
1  <span class="Negative Trend_neg">-1.3</span>   -1.3
2  <span class="Negative Trend_neg">-2.4</span>   -1.7
Sign up to request clarification or add additional context in comments.

Comments

0

I think you need mask:

hist = pd.DataFrame({'Pwer':[-.3,-1.3,-2.4], 'Trend':[1.3,-1.3,-1.7]} )
print (hist)
    Pwer  Trend
0  -0.3    1.3
1  -1.3   -1.3
2  -2.4   -1.7

hist['Pwer']=hist['Pwer'].mask((hist['Pwer']<0) & (hist['Trend']<0), 
                                hist['Pwer'].apply(lambda x:'<span class="Negative Trend_neg">{0}</span>'.format(x))) 
print (hist)
                                           Pwer  Trend
0                                          -0.3    1.3
1  <span class="Negative Trend_neg">-1.3</span>   -1.3
2  <span class="Negative Trend_neg">-2.4</span>   -1.7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.