python - 条件格式函数内的舍入
问题描述
我有以下代码可以正确格式化我的 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)
解决方案
样式器区分实际值和显示值。出于这个原因,无论 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)
)
推荐阅读
- azure - 用于删除 Blob 存储中所有文件的 Azure CLI 命令不适用于启用防火墙的 AZ 存储
- python - 在 PyPI 上上传 scipt 以获取 CLI 程序
- r - 执行 ShinyFileChoose 处理时如何停止处理直到选择文件
- javascript - 如何更改变量的范围
- c# - 使用信号器实现流
- nginx - 具有域映射的多租户应用程序的 NGINX 配置
- .net-core - 如何在运行时获取 dotnet 核心应用程序的当前进程 ID?
- javascript - 如何仅在“一个单元格”的谷歌表格中显示我的实时传感器数据?
- python - matplotlib 的 Historgram 函数返回奇怪的 y 轴值
- javascript - 如何在涉及数组或其他类型的嵌入或嵌套文档的 mongodb 更新操作中使用变量?