pandas apply style and change contents of cell

Viewed 404

For a dataframe of: enter image description here

I can apply a styling of: enter image description here

But instead, I want to drop the last value from the triplet and encode it using styling. I.e.: enter image description here

However, I do not know how to combine both steps. For pandas 25.x pandas retain styling when reformatting cells - without reparsing string to numbers demonstrates a possible answer, however, I need to get this to work for pandas 1.0.1.

df = pd.DataFrame({'foo': {'first': ['-0.89495', '0.48868', '0.06978'],
  'second': ['0.50249', '0.07999', '0.00000'],
  '3rd': ['-0.75436', '0.20239', '0.00031']},
 'bar': {'first': ['-0.49294',
   '0.61195',
   '0.42228'],
  'second': ['0.35000', '0.10999', '0.00191'],
  '3rd': ['-0.62354', '0.28775', '0.03250']}})

def highlight_significant(x, sign_level_1, sign_level_2):
    if x is np.nan:
        return ''
    else:
        if isinstance(x, list):
            p_value = float(x[2])
            if float(x[0]) > 0:
                if p_value < sign_level_2:
                    return 'font-weight: bold;background-color: lightgreen'
                elif p_value < sign_level_1:
                    color = 'lightgreen'
                    return 'background-color: %s' % color
                else:
                    return ''
            else:
                if p_value < sign_level_2:
                    return 'font-weight: bold;background-color: yellow'
                elif p_value < sign_level_1:
                    color = 'yellow'
                    return 'background-color: %s' % color
                else:
                    return ''
        else:
            return ''

display(df)

display(df.style.applymap(highlight_significant, sign_level_1=0.05, sign_level_2=0.01))

def format_regression_results(r):
    if len(r)> 1:
        coefficient = r[0]
        std_err = r[1]
        p_value = round(float(r[2]), rounding_digits)
        result = f'{round(float(coefficient), rounding_digits)} ({round(float(std_err), rounding_digits)})'        
        return result
    else:
        return '-'

df.foo = df.foo.apply(format_regression_results)
df.bar = df.bar.apply(format_regression_results)
df

edit

Indeed:

def make_float(x):
    return [float(x[0]), float(x[1]), float(x[2])]

df.foo = df.foo.apply(make_float)
df.bar = df.bar.apply(make_float)

it is possible to convert the strings to floats. enter image description here

The reformat:

styles = lambda x: df.applymap(lambda x: highlight_significant(x, sign_level_1=0.05, sign_level_2=0.01))
dx = df.applymap(lambda x: f'{x[0]}({round(float(x[1]), 2)})')
display(dx)

works. However, the styling is still lost.

1 Answers

Usiing different colors and float values the appraoch outlined from pandas retain styling when reformatting cells - without reparsing string to numbers works just fine.

def make_float(x):
    return [float(x[0]), float(x[1]), float(x[2])]

df.foo = df.foo.apply(make_float)
df.bar = df.bar.apply(make_float)

display(df)

def highlight_significant(x, sign_level_1, sign_level_2):
    if x is np.nan:
        return ''
    else:
        if isinstance(x, list):
            p_value = float(x[2])
            if float(x[0]) > 0:
                if p_value < sign_level_2:
                    return 'font-weight: bold;background-color: cyan'
                elif p_value < sign_level_1:
                    color = 'cyan'
                    return 'background-color: %s' % color
                else:
                    return ''
            else:
                if p_value < sign_level_2:
                    return 'font-weight: bold;background-color: yellow'
                elif p_value < sign_level_1:
                    color = 'yellow'
                    return 'background-color: %s' % color
                else:
                    return ''
        else:
            return ''

styles = lambda x: df.applymap(lambda x: highlight_significant(x, sign_level_1=0.05, sign_level_2=0.01))
dy = df.applymap(lambda x: f'{x[0]}({round(float(x[1]), 2)})')
display(dy)
dy.style.apply(styles, axis=None)
Related