I have a pandas dataframe:
import pandas as pd
import numpy as np
df = pd.DataFrame({'foo':[1,2, 3, 4],
'bar':[[1,2,0.04], [1,2,0.04], [1,2,0.06], np.nan]})
display(df)
def stars(x, sign_level):
if x is np.nan:
return ''
else:
p_value = x[2]
if p_value < sign_level:
return '*'
else:
return ''
df['marker'] = df.bar.apply(stars, sign_level=0.05)
df
Instead of adding a column with a star in case the result is considered significant, is it possible to format the cell (like in an Excel sheet) as bold?
display DataFrame() values in bold font in one row only seems to be able to format a whole row - I would like to reformat only a specific cell
Conditionally format Python pandas cell
seems similar, though they only change the background, not format as bold.
the code below can already change the background color - I just do not know how to format as bold.
def highlight_significant(x, sign_level):
if x is np.nan:
return ''
else:
if isinstance(x, list):
p_value = x[2]
color = 'lightgreen' if p_value < sign_level else ''
if p_value < sign_level:
return 'background-color: %s' % color
else:
return ''
else:
return ''
df.style.applymap(highlight_significant, sign_level=0.05)
This might help ...
Set up a dataframe
import pandas as pd
import numpy as np
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[0, 2] = np.nan
create functional you can apply to add bold based on a condition of you define
def negative_bold(val):
bold = 'bold' if val < 0 else ''
return 'font-weight: %s' % bold
Apply the function to the style of the data frame
s = df.style.applymap(negative_bold)
Look at the dataframe, you should find all negative numbers are bold
I looked here https://mode.com/example-gallery/python_dataframe_styling/ and here https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
EDIT Adding to this answer ...
Combining two styles
I have two functions, one to highlight yellow the number is negative and another make the number bold if negative
Negative_yellow
def negative_yellow(val):
color = 'yellow' if val < 0 else ''
return 'background-color:' + color
Negative bold
def negative_bold(val):
bold = 'bold' if val < 0 else ''
return 'font-weight: %s' % bold
I apply the two the data frame like this
df.style.\
applymap(negative_yellow).\
applymap(negative_bold)
I imagine there are more elegant ways of doing this. Hope this helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With