我正在使用 pandas Styler 类将某些列格式化为百分比。当我将输出写入 excel 时,列仍显示为浮点数。为什么我能够正确格式化和保存颜色,但不能正确设置百分比?
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)
这会产生:
df.style.format('{:.2%}').applymap(color_negative_red)
但是保存到 excel 会将百分比恢复为浮点数:
df.style.format('{:.2%}').applymap(color_negative_red).to_excel('format_test.xlsx')
该怎么办?