Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PANDAS write to csv: how to set decimal point (".", or ",")?

I can't seem to find the option to set the decimal point for floats (".", or ",") when WRITING a DataFrame to a csv file. (Reading is no problem.) My task/problem: I'm publishing a program/script and want all users independent of their OS and language settings to use it and specifically produce a csv output with THE decimal point setting as given in "locale.localeconv()["decimal_point"]". The "float_format" option has not worked for me. Do I need to convert every float to a string and replace the "." with ","? If this is posted somewhere else please excuse my mistake and provide me with the proper link.

Thank you very much for your time and effort!!

like image 533
tryptofame Avatar asked Oct 02 '22 18:10

tryptofame


1 Answers

Not going to be that efficient, but does the job (just to_csv) after)

In [29]: df = DataFrame(dict(A = [1.5,2.5], B = [2.5,3.0]))

In [30]: df
Out[30]: 
     A    B
0  1.5  2.5
1  2.5  3.0

In [31]: df.applymap(lambda x: str(x).replace('.',','))
Out[31]: 
     A    B
0  1,5  2,5
1  2,5  3,0

This should be a bit faster (needs at least 0.12)

In [37]: df.applymap(str).replace(r'\.',',',regex=True)
Out[37]: 
     A    B
0  1,5  2,5
1  2,5  3,0
like image 161
Jeff Avatar answered Oct 07 '22 20:10

Jeff