When I'm using the pandas.to_latex
function to create latex table, the column names are unfortunately not bold. What can I do to make it bold?
CodePudding user response:
Here is a complete example, this is adapted from the offical documentation.
There is a keyword to print bold columns bold_rows=True
. Sadly there isn't a kyword parameter to do the same for the columns. But I can use this to check if my code gives the same result for the column headers.
I use the result of to_latex()
and split it in three sections. One section is the line with the column names. In this line I use a regular expression to add the \text{}
-string. My code works only if you colum names don't have a whitespace.
import pandas as pd
df = pd.DataFrame(
dict(name=['Raphael', 'Donatello'],
mask=['red', 'purple'],
weapon=['sai', 'bo staff']
)
)
ans = df.to_latex(bold_rows=True)
split_middle = '\n\midrule\n'
split_top = '\\toprule\n'
top, mid = ans.split(split_middle)
start, columns = top.split(split_top)
columns = re.sub('(\w) ', '\\\\textbf{\g<0>}', columns)
result = split_middle.join([split_top.join([start, columns]), mid])
>>> result
\begin{tabular}{llll}
\toprule
{} & \textbf{name} & \textbf{mask} & \textbf{weapon} \\
\midrule
\textbf{0} & Raphael & red & sai \\
\textbf{1} & Donatello & purple & bo staff \\
\bottomrule
\end{tabular}
In the output you can see, that the header now is bold.
CodePudding user response:
Based on mosc9575's intuition to manipulate output of df.to_latex
, you can make column header is wrapped with some unique delimiters to make the substitution easier.
import re
s = re.sub('<([^>]*)>', '\\\\textbf{\g<1>}',
df.rename(columns=lambda x: f'<{x}>').to_latex(index=False))
\begin{tabular}{lll}
\toprule
\textbf{name} & \textbf{mask} & \textbf{weapon} \\
\midrule
Raphael & red & sai \\
Donatello & purple & bo staff \\
\bottomrule
\end{tabular}