简体   繁体   中英

Convert pandas dataframe to LaTeX without printing index

I'm trying to print a dataframe as a LaTeX table, but I seem to have two bad options. (Note I'm using io.formats.style.Styler.to_latex rather than dataframe.to_latex since there's a deprecation warning on the former. But dataframe.to_latex doesn't solve my issue anyway, it just changes it to a different issue.

By default the LaTeX table looks like this:

------------------------
            column name
index name
------------------------
data        data
data        data

with the name of the index one row down from the name of the column.

I can do:

df[index_as_column] = df.index
df = df.reset_index(drop=True)

So my table looks like this:

------------------------
    index_as_column column name
------------------------
0   data            data
1   data            data

The index gets printed whether I like it or not (I don't).

So my question is, how do I get a table with the column names on the same line and no index printed?

In pandas 1.4.0+ we can use pandas.io.formats.style.Styler.hide with axis='index' :

like this:

df = pd.DataFrame([[1, 2.2, "dogs"], [3, 4.4, "cats"], [2, 6.6, "cows"]],
                  index=["ix1", "ix2", "ix3"],
                  columns=["Integers", "Floats", "Strings"])
s = df.style.highlight_max(
    props='cellcolor:[HTML]{FFFF00}; color:{red};'
          'textit:--rwrap; textbf:--rwrap;'
    ).hide(axis='index')
print(s.to_latex())

to_latex has the argument index which is True by default (see https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_latex.html ). Set this one to false and you do not get the index in the output.

So

df.to_latex(index=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM