5

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!!

1

1 Answer 1

4

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

4 Comments

The first answer (using the lambda function) worked, the second did not ("TypeError: replace() got an unexpected keyword argument 'regex'" using Python 2.7.3). It is fast enough!
you need at least 0.12 for 2nd version, IIRC
note that this feature is now in 0.16.0 (releasing March 22); you can specify a decimal separator in to_csv()
years later and on a completely different issue, but you still solved it.. After transposing a dataframe (rotated = df.T), something changed in the internal representation, which caused writing to csv to fail with its decimal separator. First doing the applymap worked like a charm. Interesting for a friday afternoon project, but for now, mighty big thanks, sir!

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.