11

I want to export some DataFrames to LaTeX but these DataFrames have lots of columns, but not that many items. The solution is to display the table transposed. I know about pandas' transpose, but I want to format my rows and the method to_latex supports only formatters by column.

Some code:

import pandas as pd names = ['Bob','Jessica','Mary','John','Mel'] births = [968, 155, 77, 578, 973] tralala = [0.1, 0.2, 0.3, 0.4, 0.5] BabyDataSet = zip(names,births,tralala) df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births', 'Whatever']) df = df.transpose() print df.to_latex() 

Output:

\begin{tabular}{llllll} \toprule {} & 0 & 1 & 2 & 3 & 4 \\ \midrule Names & Bob & Jessica & Mary & John & Mel \\ Births & 968 & 155 & 77 & 578 & 973 \\ Whatever & 0.1 & 0.2 & 0.3 & 0.4 & 0.5 \\ \bottomrule \end{tabular} 

But what if I want to this for example:

\begin{tabular}{llllll} \toprule {} & 0 & 1 & 2 & 3 & 4 \\ \midrule Names & Bob & Jessica & Mary & John & Mel \\ Births & 9.7e2 & 1.6e2 & 7.7e1 & 5.8e2 & 9.7e2 \\ Whatever & 0.1 & 0.2 & 0.3 & 0.4 & 0.5 \\ \bottomrule \end{tabular} 

Is there any way to hack this functionality? Only thing I thought about was to manually apply the formats converting all my columns to strings before transposing and exporting

1 Answer 1

2

I came up with this:

for key in df.columns.values: if key in formatters: df[key] = df[key].apply(formatters[key]) print df.to_latex() 

This is pretty much equivalent to

print df.to_latex(formatters=formatters) 

and works with transposed DataFrames as well i.e. df.T.to_latex()

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.