0

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

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

4 Comments

This is a built-in feature to DataFrame.to_csv. If it's not working for you there is likely an underlying reason (e.g., outdated version of Pandas, your types are actually strings and not floats, etc.) that you should diagnose
You should add a note about the decimal argument to your answer so that others looking to solve this problem are aware of the built-in option, in case their dataset is too big to loop over every element.
@sundance, sounds like a god bit. Answer edited. Thanks.
I have pandas v0.23.3, except floats I store in my .csv files a few strings if that's the case.
2

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

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

2 Comments

It doesn't work for me, I'm still having dots in my output.csv
Works fine on my machine. What version of Python and Pandas are you running?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.