I am writing a pandas df to a csv. When I write it to a csv file, some of the elements in one of the columns are being incorrectly converted to scientific notation/numbers. For example, col_1 has strings such as '104D59' in it. The strings are mostly represented as strings in the csv file, as they should be. However, occasional strings, such as '104E59', are being converted into scientific notation (e.g., 1.04 E 61) and represented as integers in the ensuing csv file.
I am trying to export the csv file into a software package (i.e., pandas -> csv -> software_new) and this change in data type is causing problems with that export.
Is there a way to write the df to a csv, ensuring that all elements in df['problem_col'] are represented as string in the resulting csv or not converted to scientific notation?
Here is the code I have used to write the pandas df to a csv: df.to_csv('df.csv', encoding='utf-8')
I also check the dtype of the problem column: for df.dtype, df['problem_column'] is an object
Use the
float_format
argument:Which works similarly for to_csv:
If you would like to use the values as formated string in a list, say as part of csvfile csv.writier, the numbers can be formated before creating a list:
Options and Settings
For visualization of the dataframe pandas.set_option
Output of the data:
Dataframe:
And now write to_csv using the float_format='%.15f' parameter
file output:
And now write to_csv using the float_format='%f' parameter
For more details check pandas.DataFrame.to_csv