如何在Pandas转LaTeX时将整数以整数格式显示
解决Pandas导出LaTeX表格时整数显示为小数的问题
问题根源
你的CSV中存在空值(比如Transgenic Treated Mice列的P2行),导致Pandas将这些列识别为float类型,导出LaTeX时就会显示为带小数的格式(如20.000000)。同时CSV里还有20+15这类非数值字符串,需要保留原格式。
解决方案
方案1:用style.format自定义格式输出
直接在to_latex()前通过format方法指定数值列的显示规则,整数显示为整数,空值替换为空白:
修改你的代码如下:
import pandas as pd df = pd.read_csv("table.csv") # 为float类型列指定整数格式,其他列保持原样 format_rules = {col: "{:.0f}" for col in df.columns if df[col].dtype == 'float64'} # 导出时替换空值为空白字符串 tex = df.style.format(format_rules).format(na_rep='').to_latex() print("\nDataframe:") print(df) print("\nLaTeX Table Conversion:") print(tex)
方案2:读取CSV时指定列类型
使用Pandas的Int64类型(支持空值的整数类型)读取需要保留整数的列,避免自动转为float:
import pandas as pd # 定义列类型:混合内容列设为字符串,数值列用支持空值的Int64 dtype_config = { 'Transgenic Untreated Mice': str, 'Transgenic Treated Mice': 'Int64', 'Wildtype Mice': 'Int64', 'Total Mice': int } # 读取时将空字符串识别为NaN df = pd.read_csv("table.csv", dtype=dtype_config, na_values=['']) tex = df.style.format(na_rep='').to_latex() print("\nDataframe:") print(df) print("\nLaTeX Table Conversion:") print(tex)
方案3:转换现有列类型后导出
如果已读取DataFrame,可将float列转为Int64类型再导出:
import pandas as pd df = pd.read_csv("table.csv") # 把需要显示整数的float列转为支持空值的Int64类型 for col in ['Transgenic Treated Mice', 'Wildtype Mice']: df[col] = df[col].astype('Int64') tex = df.style.format(na_rep='').to_latex() print("\nDataframe:") print(df) print("\nLaTeX Table Conversion:") print(tex)
效果示例
修改后导出的LaTeX表格会显示为:
\begin{tabular}{lllllrrr} & Unnamed: 0 & Treatment & Implant & Transgenic Untreated Mice & Transgenic Treated Mice & Wildtype Mice & Total Mice \\ 0 & P1 & Armodafinil & VTA & 20+15 & 20 & 5 & 60 \\ 1 & P2 & N/A & LC & 50 & & 10 & 60 \\ 2 & P3 & Escitalopram & DR & 20 & 20 & & 40 \\ 3 & P4 & Reboxetine & LC & 20 & 20 & & 40 \\ \end{tabular}
内容的提问来源于stack exchange,提问作者TheChymera
相关产品推荐
相关产品推荐

