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} 

1 Answer 1

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} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.