Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format output data in pandas to_html

Tags:

python

pandas

I use pandas' to_html to generate output file, when data are written to the file they have many digits after the decimal point. The pandas' to_html float_format method can limit the digits, but when I used 'float_format' as below:

DataFormat.to_html(header=True,index=False,na_rep='NaN',float_format='%10.2f')

it raise a exception:

typeError: 'str' object is not callable

how to solve this problem?

like image 964
wuwucat Avatar asked Feb 15 '13 17:02

wuwucat


People also ask

How to export a pandas Dataframe to an HTML file?

Let's write Pandas DataFrame in an HTML file. This can be achieved by using the to_html () method. The to_html () takes the path of the file you want the data exported to. If you don't provide an absolute path, it would save a file relative to the current directory. You can export a DataFrame to an HTML table like this:

How to read tabular data from HTML file in pandas?

We can render tabular data using HTML's <table> element. The Pandas data analysis library provides functions like read_html () and to_html () so we can import and export data to DataFrames. In this article, we will learn how to read tabular data from an HTML file and load it into a Pandas DataFrame.

How to add formatting to <td> tags in pandas?

A possible solution would be to attach a CSS class to <td> tags in the HTML output, which could be then formatted using CSS stylesheet. The above would then become: Edit: As suggested by @Andy-Hayden I can add formatting by simply replacing stars with <span class="signifcant">...</span> in my example: Newer versions of pandas escape the tags.

How to render a pandas Dataframe to a table in Python?

Last Updated : 29 Aug, 2020 Pandas in Python has the ability to convert Pandas DataFrame to a table in the HTML web page. pandas.DataFrame.to_html () method is used for render a Pandas DataFrame. Syntax : DataFrame.to_html () Return : Return the html format of a dataframe.


2 Answers

Without a lambda, you can pass a str.format function directly:

df = pd.DataFrame(...)
df.to_html(float_format='{:10.2f}'.format)
like image 149
Serge Rogatch Avatar answered Oct 07 '22 22:10

Serge Rogatch


From the to_html docs:

float_format : one-parameter function, optional
    formatter function to apply to columns' elements if they are floats
    default None

You need to pass a function. For example:

>>> df = pd.DataFrame({"A": [1.0/3]})
>>> df
          A
0  0.333333

>>> print df.to_html()
<table border="1" class="dataframe">
    <tr>
      <th>0</th>
      <td> 0.333333</td>
    </tr>
[...]

but

>>> print df.to_html(float_format=lambda x: '%10.2f' % x)
<table border="1" class="dataframe">
[...]
    <tr>
      <th>0</th>
      <td>      0.33</td>
    </tr>
[...]
like image 27
DSM Avatar answered Oct 07 '22 23:10

DSM