首页 > 解决方案 > 条件格式函数内的舍入

问题描述

我有以下代码可以正确格式化我的 df,只是它将我的值的舍入从 2 dp 更改为向每个值添加 4 个零。任何人都知道如何调整功能以不添加小数位?

这是桌子

data = ''
index = ['US 2yr','US 5yr','US 10yr','US Ultra']
columns = ['Total Positioning - Z Score',
         'Asset Manager Positioning - Z Score',
         'Levereged Fund Positioning - Z Score',
         'Dealer Positioning - Z Score']
table_6m = pd.DataFrame(data,index=index,columns=columns)

table_6m.iloc[0,0] = 1.72
table_6m.iloc[0,1] = 1.56
table_6m.iloc[0,2] = 0.65
table_6m.iloc[0,3] = -1.26

table_6m.iloc[1,0] = 0.02
table_6m.iloc[1,1] = 0.25
table_6m.iloc[1,2] = -0.11
table_6m.iloc[1,3] = 1.99

table_6m.iloc[2,0] = -2.75
table_6m.iloc[2,1] = 1.49
table_6m.iloc[2,2] = 0.17
table_6m.iloc[2,3] = -0.02

table_6m.iloc[3,0] = 3.03
table_6m.iloc[3,1] = -0.22
table_6m.iloc[3,2] = 0.85
table_6m.iloc[3,3] = -1.50

这是执行条件格式的功能

def background_gradient(s, m=None, M=None, cmap='Oranges', low=0, high=0):
    print(s.shape)
    if m is None:
        m = s.min().min()
    if M is None:
        M = s.max().max()
    rng = M - m
    norm = colors.Normalize(m - (rng * low),
                        M + (rng * high))
    normed = s.apply(lambda x: norm(x.values))

    cm = plt.cm.get_cmap(cmap)
    c = normed.applymap(lambda x: colors.rgb2hex(cm(x)))
    ret = c.applymap(lambda x: 'background-color: %s' % x)
    return ret


table_6m.style.apply(background_gradient, axis=None)

标签: pythonpandasdataframepandas-styles

解决方案


样式器区分实际值和显示值。出于这个原因,无论 DataFrame 中存储的数据如何,您都需要指定格式样式以防止默认的格式化行为。

要么设置precision

(
    table_6m.style
        .apply(background_gradient, axis=None)
        .format(precision=2)
)

或者使用格式化功能:

(
    table_6m.style
        .apply(background_gradient, axis=None)
        .format(formatter='{:.2f}'.format)
)

格式化表格


推荐阅读