Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Locale format not working in style.format()

I want to render a pandas.Dataframe with locale "de_DE.UTF-8", having a "," as decimal point and "." as thousand separator. When simply running locale.format, I get expected results. But when adding the same expression as pandas formatter nothing changes in rendered html (although, no error is thrown). Example code:

import pandas
import locale

locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
print(locale.format('%.2f', 1000.245, True))
print(locale.format('%.2f', 10000000.22655, True))

df = pandas.DataFrame({'a': [1000.245, 10000000.22655]})
style = df.style.format(formatter=lambda x: f'{locale.format("%.2f", x, True)} €')
print(style.render())

Gives output:

1.000,25
10.000.000,23
<style  type="text/css" >
</style>  
<table id="T_f0ae1678_3e71_11e9_8f47_d0bf9ce00d56" > 
<thead>    <tr> 
        <th class="blank level0" ></th> 
        <th class="col_heading level0 col0" >a</th> 
    </tr></thead> 
<tbody>    <tr> 
        <th id="T_f0ae1678_3e71_11e9_8f47_d0bf9ce00d56level0_row0" class="row_heading level0 row0" >0</th> 
        <td id="T_f0ae1678_3e71_11e9_8f47_d0bf9ce00d56row0_col0" class="data row0 col0" >1000.25 €</td> 
    </tr>    <tr> 
        <th id="T_f0ae1678_3e71_11e9_8f47_d0bf9ce00d56level0_row1" class="row_heading level0 row1" >1</th> 
        <td id="T_f0ae1678_3e71_11e9_8f47_d0bf9ce00d56row1_col0" class="data row1 col0" >10000000.23 €</td> 
    </tr></tbody> 
</table>

Does pandas set up its own locale? Or what am I missing? Thx

like image 430
Henhuy Avatar asked Mar 04 '19 11:03

Henhuy


People also ask

How do I use conditional formatting in pandas?

One way to conditionally format your Pandas DataFrame is to highlight cells which meet certain conditions. To do so, we can write a simple function and pass that function into the Styler object using . apply() or .


1 Answers

This seems to be a bug in older pandas versions (<2020), update your pandas.

Version: '1.1.3' outputs:

<style  type="text/css" >
</style><table id="T_82df8768_b9b1_11eb_a80f_88d7f6c760ad" ><thead>    <tr>        <th class="blank level0" ></th>        <th class="col_heading level0 col0" >a</th>    </tr></thead><tbody>
                <tr>
                        <th id="T_82df8768_b9b1_11eb_a80f_88d7f6c760adlevel0_row0" class="row_heading level0 row0" >0</th>
                        <td id="T_82df8768_b9b1_11eb_a80f_88d7f6c760adrow0_col0" class="data row0 col0" >1.000,25 €</td>
            </tr>
            <tr>
                        <th id="T_82df8768_b9b1_11eb_a80f_88d7f6c760adlevel0_row1" class="row_heading level0 row1" >1</th>
                        <td id="T_82df8768_b9b1_11eb_a80f_88d7f6c760adrow1_col0" class="data row1 col0" >10.000.000,23 €</td>
            </tr>
    </tbody></table>
like image 67
Andreas Avatar answered Nov 02 '22 23:11

Andreas