Search code examples
pythonpandascsvnumber-formatting

Python pandas preserving decimal commas in the output csv file


I'm using pandas library to do some operations on .csv file.

Input file input.csv:

    A    B   
   1,2  2,2
   3,5  5,4 

My code:

import pandas as pd

df = read_csv('input.csv', sep = ';', encoding = 'ANSI', decimal = ',')
'''
some operations on cells like adding, multiplying...  
'''

df.to_csv('output.csv', sep = ';', encoding = 'ANSI', index = False)

And here is how my output.csv looks like:

    A    B    C   
   1.2  2.2  6.5
   3.5  5.4  7.8

But is there any way to keep my decimal separator as comma like there was in the input.csv?

Here is how output.csv should look like:

    A    B    C   
   1,2  2,2  6,5
   3,5  5,4  7,8 

I have tried something like this but it didn't work:

df = df.astype(str).replace('.',',')

Solution

  • Method 1

    You can use:

    df.to_csv('output.csv', sep = ';', encoding='ANSI', index=False, decimal=",")
    

    Method 2

    As an alternative you can also use.

    df = df.applymap(lambda x: str(x).replace('.',','))
    

    instead of df = df.astype(str).replace('.',',')

    It would give:

          A   B   C
    0   1,2 2,2 6,5
    1   3,5 5,4 7,8
    

    And then

    df.to_csv('output.csv', sep = ';', encoding = 'ANSI', index=False)