You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Bokeh图表如何为字符串列与n个浮点列设置不同格式?

在Bokeh表格中为不同类型列设置差异化格式

完全可以给字符串列和浮点列设置不同的显示格式,Bokeh的TableColumn允许为每一列单独指定格式化器,以下是具体实现方法:

核心思路

  • 字符串列使用StringFormatter,可设置字体样式、对齐方式等样式类配置
  • 浮点列使用NumeralFormatter,支持自定义数值格式(如小数位数、千分位、货币符号等)
  • 通过列表拼接的方式,分别生成字符串列和浮点列的TableColumn列表,再合并为最终列配置

完整示例代码

import pandas as pd
from bokeh.models import DataTable, TableColumn, StringFormatter, NumeralFormatter
from bokeh.plotting import show

# 构造示例数据
df_left = pd.DataFrame({
    "姓名": ["张三", "李四", "王五"],
    "部门": ["研发部", "市场部", "人事部"],
    "职位": ["工程师", "经理", "专员"]
})
df_right = pd.DataFrame({
    "月薪": [12500.50, 18750.75, 9200.20],
    "年终奖": [37500.00, 56250.00, 27600.00]
})
# 合并两个DataFrame
df = pd.concat([df_left, df_right], axis=1)

# 生成列配置:字符串列和浮点列分别设置格式
columns = [
    # 字符串列:设置斜体字体
    TableColumn(field=col, title=col, format=StringFormatter(font_style="italic")) 
    for col in df_left.columns
] + [
    # 浮点列:月薪保留两位小数,年终奖显示带千分位的整数
    TableColumn(field=col, title=col, format=NumeralFormatter(format="0.00" if col == "月薪" else "0,0")) 
    for col in df_right.columns
]

# 创建表格并展示
data_table = DataTable(source=df, columns=columns, width=800, height=300)
show(data_table)

关键说明

  • 修正了你示例代码中的语法错误:原代码将两个列表推导式用逗号放在一个列表中会触发语法错误,正确做法是用+拼接两个列表
  • NumeralFormatter的format参数支持多种格式字符串,常用示例:
    • "0.00":保留两位小数
    • "0,0":显示千分位分隔符
    • "$0,0.00":添加美元符号并保留两位小数
  • StringFormatter支持font_style、text_align、font_size等样式设置

内容的提问来源于stack exchange,提问作者user15169637

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:22:44