Search code examples
pythonpandasdecimal-point

In Pandas How To Invert Decimal Notation?


In python3 and pandas I have a dataframe with float values that are displayed like this:

import pandas as pd

df_despesas = pd.read_csv("resultados/despesas_dep_est_sp_julho.csv", sep=',',encoding = 'utf-8', converters={'CNPJ': lambda x: str(x), 'cnpj_raiz_fornecedor': lambda x: str(x), 'Ano': lambda x: str(x)}, decimal=',')

#Configuration to show float with two decimals
pd.options.display.float_format = '{:,.2f}'.format

df_despesas.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 455156 entries, 0 to 455155
Data columns (total 9 columns):
Ano                     455156 non-null object
CNPJ                    455156 non-null object
Deputado                455156 non-null object
Fornecedor              455156 non-null object
Matricula               455156 non-null object
Mes                     455156 non-null object
Tipo                    455156 non-null object
Valor                   455156 non-null float64
cnpj_raiz_fornecedor    455156 non-null object
dtypes: float64(1), object(8)
memory usage: 31.3+ MB

df_despesas.reset_index().Valor.head()
0     200.00
1     295.40
2   2,850.00
3     100.00
4     195.01

"${:,.2f}".format(df_despesas.Valor.sum())
'$311,900,200.82'

I would like these numbers to appear with dot separating the thousands and comma the cents. Like this:

0     200,00
1     295,40
2   2.850,00
3     100,00
4     195,01

'$311.900.200,82'

Please, does anyone know how I should do it?


Solution

  • I think the simplest way to achieve what you are looking for, i.e. dot separating the thousands and comma the cents would be to use string manipulation. You can create a new function to do so and then use apply to apply it on the respective dataframe column

    x = [200, 295.40, 2850, 100, 195.01]
    df = pd.DataFrame(x, columns=["value"])
    df.value = df.value.map('{:,.2f}'.format)
    df
          value
    0    200.00
    1    295.40
    2  2,850.00
    3    100.00
    4    195.01
    

    now create a function to change dots to commas and commas to dots and apply it to the dataframe column

    def change_format(x):
        return str(x).replace('.', '/').replace(',', '.').replace('/', ',')
    
    df.value = df.value.apply(change_format)
    df  
          value
    0    200,00
    1    295,40
    2  2.850,00
    3    100,00
    4    195,01