mactonight95
mactonight95

Reputation: 15

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('.',',')

Upvotes: 0

Views: 3897

Answers (2)

sundance
sundance

Reputation: 2945

Like pandas.read_csv, DataFrame.to_csv also has a decimal argument:

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

Upvotes: 2

harpan
harpan

Reputation: 8631

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)

Upvotes: 4

Related Questions