0

I follow up on this question. Assume I have the following dataframe.

df = pd.DataFrame({'col1': [1, 3], 'col2': [2, 1]})

from which I can get a Latex table as

df.to_latex()

I know I can pass a formatter for each columnm as illustrated, e.g., in the above question. My question is: How can I format the elements of col1 based on the elements of col2 and viceversa?

Assume, for example, I want to add a plus sign to a cell, if its value is higher than that of the adjacent cell, getting the following result.

\begin{tabular}{lrr}
\toprule
{} &  col1 &  col2 \\
\midrule
0 &     1 &     +2 \\
1 &     +3 &     1 \\
\bottomrule
\end{tabular}
k88074
  • 2,042
  • 5
  • 29
  • 43

1 Answers1

0

It looks like the formatters only accept functions that work on cell values without any information about the dataframe index/column. So it might not work for your purpose.

I would pre-format the data and pass to to_latex:

strs = np.array([['','+']]* len(df))
signs =  np.where(df['col1'].lt(df['col2']).values[:,None], strs,strs[:,::-1])

(signs + df.astype(str)).to_latex()

Output:

\begin{tabular}{lll}
\toprule
{} & col1 & col2 \\
\midrule
0 &    1 &   +2 \\
1 &   +3 &    1 \\
\bottomrule
\end{tabular}
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74