2013-02-15 24 views
6

Io uso pandas 'to_html per generare il file di output, quando i dati vengono scritti nel file hanno molte cifre dopo il punto decimale. I panda to_html metodo float_format possono limitare le cifre, ma quando ho usato 'float_format' come di seguito:dati di output in formato pandas to_html

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

è sollevare un eccezione:

typeError: 'str' object is not callable 

come risolvere questo problema?

risposta

10

Dalle to_html documentazione:

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

è necessario passare una funzione. Per esempio:

>>> 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> 
[...] 

ma

>>> 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> 
[...]