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

隐藏索引后Pandas转LaTeX时最后一列列名未加粗的临时解决办法

临时解决Pandas隐藏索引后列名无法全部加粗的问题

针对你遇到的这个Pandas bug(隐藏索引后,applymap_index设置列名加粗时最后一列失效),这里提供几个临时解决办法:

方法1:修改生成的LaTeX字符串

直接对生成的LaTeX代码做字符串替换,给最后一列列名加上\bfseries:

import pandas as pd

df = pd.DataFrame(
    dict(name=['Raphael', 'Donatello'],
         mask=['red', 'purple'],
         weapon=['sai', 'bo staff']
        )
)

# 生成LaTeX代码
latex_str = df.style.hide(axis="index").applymap_index(lambda v: "font-weight: bold;", axis="columns").to_latex(convert_css=True)

# 找到表头行,给最后一列添加粗体格式
lines = latex_str.split('\n')
for i, line in enumerate(lines):
    if '\bfseries' in line and line.endswith('\\\\'):
        # 分割表头项
        parts = line.split(' & ')
        # 给最后一项加上\bfseries
        parts[-1] = f'\\bfseries {parts[-1].strip().replace("\\\\", "")} \\\\'
        lines[i] = ' & '.join(parts)
        break

fixed_latex = '\n'.join(lines)
print(fixed_latex)

方法2:先保留索引生成LaTeX,再移除索引相关内容

先生成带索引的LaTeX(此时所有列名都能正常加粗),再手动删除索引列的内容:

import pandas as pd

df = pd.DataFrame(
    dict(name=['Raphael', 'Donatello'],
         mask=['red', 'purple'],
         weapon=['sai', 'bo staff']
        )
)

# 生成带索引的LaTeX
latex_str = df.style.applymap_index(lambda v: "font-weight: bold;", axis="columns").to_latex(convert_css=True)

# 处理LaTeX代码,移除索引列
lines = latex_str.split('\n')
fixed_lines = []
for line in lines:
    if line.startswith('\\begin{tabular}'):
        # 减少一个列(从llll改成lll)
        fixed_lines.append(line.replace('llll', 'lll'))
    elif line.startswith(' & \\bfseries'):
        # 移除表头的空索引单元格
        fixed_lines.append(line[2:])
    elif line.startswith(('0 & ', '1 & ')):
        # 移除每行的索引值
        fixed_lines.append(line[2:])
    else:
        fixed_lines.append(line)

fixed_latex = '\n'.join(fixed_lines)
print(fixed_latex)

方法3:使用set_table_styles替代applymap_index

通过定义表头的全局样式来设置粗体,避开applymap_index的bug:

import pandas as pd

df = pd.DataFrame(
    dict(name=['Raphael', 'Donatello'],
         mask=['red', 'purple'],
         weapon=['sai', 'bo staff']
        )
)

# 定义表头样式
style = df.style.hide(axis="index").set_table_styles([
    {'selector': 'th.col_heading', 'props': [('font-weight', 'bold')]}
])

print(style.to_latex(convert_css=True))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:00:08