I am using the pandas Styler class to format some columns as a percent. When I write the output to excel, the columns are still showing up as floats. Why am I able to format and save colors properly, but not percents?
import pandas as pd
import numpy as np
def color_negative_red(val):
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
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)
This produces this:
df.style.format('{:.2%}').applymap(color_negative_red)
But saving to excel reverts the percents back to floats:
df.style.format('{:.2%}').applymap(color_negative_red).to_excel('format_test.xlsx')
What to do?